繁体   English   中英

如何通过onClick在函数中获取React组件

[英]How to get a React component in a function by onClick

我需要获得一个我喜欢的组件并查看其目标属性。 我尝试获取它,但evt参数未定义

  getcomponent(evt){

  console.log(evt.target)
  //...

  }

//...

  render() {

      return (<button id="btn" onClick={() =>this.getcomponent()}></button>);
  }

event作为参数添加到onClick

render() {
    return (<button id="btn" onClick={(event) =>this.getcomponent(event)}></button>);
}

您没有将事件传递给函数调用。 通过这样的事件: onClick={(evt) => this.getcomponent(evt)}

使代码简短:

onClick = event => {
  console.log(event.target)
}
render() {
  return <button id="btn" onClick={this.onClick}></button>
}

您需要传递事件才能恢复原状。 这是代码。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM