多个层次结构中的事件句柄React

Event handles in multiple hierarchies React

本文关键字:事件 句柄 React 层次结构      更新时间:2023-09-26

我有一个包装按钮的第三方组件:

<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?

(假设我可以更改第三方组件(我可以分叉并更改它))

您不需要从组件中删除或更新点击处理程序。只要阻止事件发生就行了。

如果按钮呈现在具有单击处理程序的div中,那么可以防止单击事件传播到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
  }
}