Javascript React - 如何仅捕获父级的 onClick 事件而不捕获子级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34349136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:12:02  来源:igfitidea点击:

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

javascriptdomreactjs

提问by Daniel Calderon Mori

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

我有一个 React 组件的一部分,如下所示:

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

And a click handler for the thelement:

以及th元素的点击处理程序:

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

I want to capture the thelement. It works fine when headerElementis 'some string', but when it is an inputelement, the inputelement is the one referenced in the event.targetproperty.

我想捕获th元素。当headerElement是“某个字符串”时它工作正常,但是当它是一个input元素时,该input元素是event.target属性中引用的元素。

What's the best way to achieve this?

实现这一目标的最佳方法是什么?

回答by Arun P Johny

Since you are binding the handler to thyou can use the currentTargetproperty. The targetproperty refers to the element which dispatched the event.

由于您将处理程序绑定到th您可以使用currentTarget属性。将目标物业是指调度事件的元素。

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

回答by nghiepit

Check them

检查它们

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

回答by Bhojendra Rauniyar

Like this?

像这样?

event.target.parentNode

回答by Sabir Hussain

simply use event.currentTarget

只需使用event.currentTarget

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