最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cancel onClick event of parent component in child component in React - Stack Overflow

programmeradmin1浏览0评论

I have a ponent that looks like:

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

If I click on the ChildComponent, both doSomethingElse and doSomething fire. How can I cancel the parent ponent onClick event propagation when the child onClick event fires?

I have a ponent that looks like:

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

If I click on the ChildComponent, both doSomethingElse and doSomething fire. How can I cancel the parent ponent onClick event propagation when the child onClick event fires?

Share Improve this question edited Jul 29, 2017 at 18:44 Andy Baird asked Jul 26, 2017 at 17:37 Andy BairdAndy Baird 6,2284 gold badges45 silver badges64 bronze badges 2
  • Possible duplicate of jQuery / Bootstrap: Child DIV opens up Parent Modal – Shubham Khatri Commented Jul 26, 2017 at 18:03
  • No it's not even a little bit. – Andy Baird Commented Jul 26, 2017 at 22:00
Add a ment  | 

2 Answers 2

Reset to default 13

You should add the line e.stopPropagation(); to the top of your this.doSomethingElse event handler.

Event.stopPropagation().

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

So when you use e.StopPropagation() in an event handler it prevents the event from bubbling up to ancestors and triggering their event handlers.

Make sure to include e as an argument of your this.doSomethingElse method.

doSomethingElse( e ) {
  e.stopPropagation();
  // ... do stuff
}

If you wish to avoid duplicating events, use stopPropagation function.

class App extends React.Component {
  
  firstHandle = () => {
    console.log('parent');
  }
  
  secondHandle = (e) => {
    e.stopPropagation();
    console.log('child');
  }
  
  render() {
    return (
      <div onClick={this.firstHandle}>
        Parent
        <div onClick={this.secondHandle}>child</div>
      </div>
    );
  }
}


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

发布评论

评论列表(0)

  1. 暂无评论