React - how to capture only parent's onClick event and not children

馋奶兔 提交于 2020-05-09 19:22:12

问题


I have part of a React Component that looks like this:

var headerElement = someBoolean ? <input/> : 'some string';
return <th onClick={this._onHeaderClick}>{headerElement}</th>;

And a click handler for the th element:

_onHeaderClick(event) {
    event.preventDefault();
    console.log(event.target);
},

I want to capture the th element. It works fine when headerElement is 'some string', but when it is an input element, the input element is the one referenced in the event.target property.

What's the best way to achieve this?


回答1:


Since you are binding the handler to th you can use the currentTarget property. The target property refers to the element which dispatched the event.

_onHeaderClick(event) {
    event.preventDefault();
    console.log(event.currentTarget);
}



回答2:


Check them

_onHeaderClick(event) {
   event.preventDefault();
   if(event.target === event.currentTarget) {
      // handle
   }
}



回答3:


Like this?

event.target.parentNode



回答4:


simply use event.currentTarget

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


来源:https://stackoverflow.com/questions/34349136/react-how-to-capture-only-parents-onclick-event-and-not-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!