[英]How to get a React component in a function by onClick
I need to get a component that I cliked and see its target property. 我需要获得一个我喜欢的组件并查看其目标属性。 I try to get it but the evt param is undefined
我尝试获取它,但evt参数未定义
getcomponent(evt){
console.log(evt.target)
//...
}
//...
render() {
return (<button id="btn" onClick={() =>this.getcomponent()}></button>);
}
Add event
as a parameter to the onClick
: 将
event
作为参数添加到onClick
:
render() {
return (<button id="btn" onClick={(event) =>this.getcomponent(event)}></button>);
}
You didn't pass the event to function call. 您没有将事件传递给函数调用。 Pass the event like this:
onClick={(evt) => this.getcomponent(evt)}
. 通过这样的事件:
onClick={(evt) => this.getcomponent(evt)}
。
Make code short and simple: 使代码简短:
onClick = event => {
console.log(event.target)
}
render() {
return <button id="btn" onClick={this.onClick}></button>
}
You need to pass event in order to get it back. 您需要传递事件才能恢复原状。 Here is the code.
这是代码。
class TestJS extends React.Component { constructor(props) { super(props); this.getcomponent = this.getcomponent.bind(this); } getcomponent(event){ console.log(event.target); } render() { return( <div id="root"> <button id="btn" onClick={(event) =>this.getcomponent(event)}></button>; </div> )}; } export default TestJS;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.