关于javascript:在React中取消子组件中父组件的onClick事件

Cancel onClick event of parent component in child component in React

我有一个看起来像这样的组件:

1
2
3
<ParentComponent onClick={this.doSomething}>
  <ChildComponent onClick={this.doSomethingElse} />
</Parent>

如果我点击 ChildComponent,doSomethingElse 和 doSomething 都会触发。当子 onClick 事件触发时,如何取消父组件 onClick 事件传播?


您应该将行 e.stopPropagation(); 添加到 this.doSomethingElse 事件处理程序的顶部。

Event.stopPropagation().

Prevents further propagation of the current event in the capturing and bubbling phases.

因此,当您在事件处理程序中使用 e.StopPropagation() 时,它可以防止事件冒泡到祖先并触发它们的事件处理程序。

确保包含 e 作为 this.doSomethingElse 方法的参数。

1
2
3
4
doSomethingElse( e ) {
  e.stopPropagation();
  // ... do stuff
}


如果您希望避免重复事件,请使用 stopPropagation 函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class App extends React.Component {
 
  firstHandle = () => {
    console.log('parent');
  }
 
  secondHandle = (e) => {
    e.stopPropagation();
    console.log('child');
  }
 
  render() {
    return (
     
        Parent
        child
     
    );
  }
}


ReactDOM.render(
  <App />,
  document.getElementById("react")
);
1
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js">