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

时间:2015-11-26 10:34:09

标签: 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上的子组件(按钮),然后继续(或不继续)onPoint上的ExtComponent?

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

1 个答案:

答案 0 :(得分:2)

您不需要从组件中删除或更新点击处理程序。只是阻止事件到达那里。

如果按钮在具有点击处理程序的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
  }
}
相关问题