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
React - how to capture only parent's onClick event and not children
提问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 th
element:
以及th
元素的点击处理程序:
_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.
我想捕获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 th
you 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
onClick(e) {
e.preventDefault();
console.log(e.currentTarget);
}