我有一个包装按钮的第三方组件:
<ExtComponent> <!-- this component has it's own internal onClick handler -->
<button />
</ExtComponent>
该组件有一个内部 onClick
优先于我尝试添加到 <button>
的任何 onClick 的事件处理程序。所以当我这样做时
<ExtComponent> <!-- this component has it's own internal onClick handler -->
<button onClick={this.onClick} /> <!-- this is not being triggered as ExtComponent onClick is being called instead -->
</ExtComponent>
我的组件 onClick 没有被调用。
有没有办法先处理子组件(按钮)onClick,然后继续(或不)处理ExtComponent onClick?
(假设我可以更改第 3 方组件(我可以 fork 并更改它))
最佳答案
您不需要从组件中删除或更新点击处理程序。只需阻止事件到达那里即可。
如果按钮在具有点击处理程序的 div 内呈现,那么您可以 prevent the click event from propagating直到 div。
onClick: function(event) {
event.stopPropagation();
// now handle the click
}
如果您希望允许事件在某些条件下传播,则只需不要停止传播即可。
onClick: function(event) {
if(this.prop.foo == 'bar') {
event.stopPropagation();
} else {
// let the event trigger the upper event listeners too
}
}
关于javascript - 多个层次结构中的事件句柄 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936343/