简体   繁体   中英

React event.target is not the element I set event Listener on

 const onClick = (e) => { console.log(e.target); } const App = () => ( <button name={'YES'} className="btn waves-effect waves-light left blue darken-4" onClick={onClick} > Yes <i className='material-icons left'>done</i> </button> ); ReactDOM.render(<App />, document.querySelector("#app")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script> <div id="app"> 

I need e.target to be <button> in all possible cases, but when I click on <i> (or any other element as it seems), the target is <i> respectively. Its probably not error, but i don't know what to do about it.

Use event.currentTarget , which will always be the element on which the handler was added. event.target will always be the element on which the event occurred.

<button
  name={answerTypes.YES}
  className="btn waves-effect waves-light left blue darken-4"
  onClick={this.onClick}
>
  Yes
  <i className='material-icons left'>done</i>
</button>

onClick(e) {
  console.log(e.currentTarget);
}

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