Javascript 如何检测哪个 React 组件触发 onKeyUp 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35862979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect which React component triggers onKeyUp event?
提问by Daniel May
Let's say we have a single onKeyUp
handler:
假设我们有一个onKeyUp
处理程序:
handleKeyUp: function(e) {
/* handle stuff */
},
And we have a couple of input components, both of which could trigger the handler:
我们有几个输入组件,它们都可以触发处理程序:
<input type="text" ref="login" onKeyUp={this.handleKeyUp} />
...
<input type="text" ref="pwd" onKeyUp={this.handleKeyUp} />
How do I make it so the handler can detect if the onKeyUp
was triggered from login
or pwd
?
我如何做到这一点,以便处理程序可以检测onKeyUp
是从login
或触发的pwd
?
A scenario is where I detect a tab press on pwd
and then I proceed to try to save the text fields (but not where I tab off from login
).
一个场景是我检测到一个选项卡按下pwd
,然后我继续尝试保存文本字段(但不是我从哪个选项卡关闭login
)。
I've tried looking into detail of e.target
but couldn't figure out how to reference the originating component.
我试过查看详细信息,e.target
但无法弄清楚如何引用原始组件。
Update
更新
Sorry, must not be thinking clearly. Yes, e.target
is a reference to the originating component. I was looking to get a handle on ref
to get the value. But I don't need the ref, I can just get the value from e.target.value
.
对不起,一定没有想清楚。是的,e.target
是对原始组件的引用。我正在寻找一个处理ref
来获得价值。但我不需要 ref,我可以从e.target.value
.
采纳答案by mr-wildcard
As stated in React's Event System
documentation:
Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.
您的事件处理程序将传递 SyntheticEvent 的实例,这是一个围绕浏览器本机事件的跨浏览器包装器。它与浏览器的本机事件具有相同的界面,包括 stopPropagation() 和 preventDefault(),但这些事件在所有浏览器中的工作方式相同。
Thus, an instance of a SyntheticEvent
is passed to your callback
因此, a 的一个实例SyntheticEvent
被传递给你的回调
handleKeyUp: function(event) {
/* event is an instance of SyntheticEvent
from wich you can extract the currentTarget
*/
},
Edit: In case you really want to access component's ref
name before doing anything, here is how you could do it in ES6 :
编辑:如果你真的想ref
在做任何事情之前访问组件的名称,这里是你在 ES6 中可以这样做的方法:
class MyComponent extends React.Component {
constructor() {
super();
this.handleLoginKeyUp = this.keyUpHandler.bind(this, 'LoginInput');
this.handlePwdKeyUp = this.keyUpHandler.bind(this, 'PwdInput');
}
keyUpHandler(refName, e) {
console.log(refName);
// prints either LoginInput or PwdInput
}
render() {
return (
<div>
<input type="text" onKeyUp={this.handleLoginKeyUp} ref="LoginInput" />
<input type="text" onKeyUp={this.handlePwdKeyUp} ref="PwdInput" />
</div>
);
}
}