反应-防止父母触发孩子的事件触发 [英] React - Prevent Event Trigger on Parent From Child
问题描述
我有这种情况,当单击父元素时,它会翻转以显示具有不同颜色的子元素。不幸的是,当用户单击其中一种颜色时,也会触发父级上的 click事件。
I have this scenario, where when parent element is clicked, it flips to show a child element with different colours. Unfortunately, when the user clicks on one of the colours, the 'click' event on parent is also triggered.
如何停止父级上的事件触发当孩子被点击时?
可能的解决方案我想知道:
Possible solutions I am wondering:
-
CSS ?
单击子项时,将pointer-events:none
类附加到父项。但是,这意味着以后将需要清除父级的指针事件
类。
CSS?
Appendpointer-events : none
class to the parent when the child is clicked. However, this would mean that the parent will need to be cleansed of thepointer-events
class later.
使用引用吗?
记录父级反应$ c $的
ref
c>元素和在点击孩子时,将 event.target
与参考进行比较?我不喜欢这样,因为我不喜欢全局 ref
。
Using Ref?
Record the ref
of the parent React
element & upon click on the child, compare the event.target
against the ref? I don't like this because I don't like the global ref
.
这种想法和更好的解决方案将不胜感激。问题是:
单击子项时如何停止父项上的事件触发器?
Thoughts and the better solution would be much appreciated. The question is: How can I stop the event trigger on parent when the child is clicked?
推荐答案
stopPropagation
-防止当前事件在$中进一步传播b $ b起泡阶段
stopPropagation
- Prevents further propagation of the current event in the bubbling phase
var App = React.createClass({
handleParentClick: function (e) {
console.log('parent');
},
handleChildClick: function (e) {
e.stopPropagation();
console.log('child');
},
render: function() {
return <div>
<p onClick={this.handleParentClick}>
<span onClick={this.handleChildClick}>Click</span>
</p>
</div>;
}
});
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
这篇关于反应-防止父母触发孩子的事件触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!