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

标签 javascript reactjs

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

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

相关文章:

javascript - 运行 create react app 时未定义“render”

javascript - iPython/Jupyter 笔记本 : How to Embed Interactive Graph Using Desmos API?

javascript - React-Boilerplate 在没有端口的情况下运行生产

javascript - 无法读取未定义的属性 '0' - 卡在 reactjs 教程中

javascript - React/Redux 组件,需要根据下拉选择填充一定数量的字段

javascript - Google Maps API - 未定义热图( map 显示但无法更改)

javascript - 如何递归地将数组中的每n个元素传递到函数中

javascript - 如何在javascript变量中存储单选按钮值?

reactjs - 带有 React 的 Redux-firestore

javascript - 如何使用循环构建 JSX