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 事件传播?
您应该将行
Event.stopPropagation().
Prevents further propagation of the current event in the capturing and bubbling phases.
因此,当您在事件处理程序中使用
确保包含
1 2 3 4 | doSomethingElse( e ) { e.stopPropagation(); // ... do stuff } |
如果您希望避免重复事件,请使用
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"> |