简体   繁体   中英

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

  getcomponent(evt){

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

  }

//...

  render() {

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

Add event as a parameter to the 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)} .

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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