Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

javascript - React - Prevent Event Trigger on Parent From Child

I have this scenario, where when parent element is clicked, it flips to show a child element with different colours. Unfortunately, when the user clicks on one of the colours, the 'click' event on parent is also triggered.

How can I stop the event trigger on parent when the child is clicked?

Possible solutions I am wondering:

  1. CSS?
    Append pointer-events : none class to the parent when the child is clicked. However, this would mean that the parent will need to be cleansed of the pointer-events class later.

  2. Using Ref?
    Record the ref of the parent React element & upon click on the child, compare the event.target against the ref? I don't like this because I don't like the global ref.

Thoughts and the better solution would be much appreciated. The question is: How can I stop the event trigger on parent when the child is clicked?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use stopPropagation

stopPropagation - Prevents further propagation of the current event in the bubbling phase

var App = React.createClass({
  handleParentClick: function (e) { 
    console.log('parent');
  },

  handleChildClick: function (e) {
    e.stopPropagation();
    console.log('child');
  },

  render: function() {
    return <div>
      <p onClick={this.handleParentClick}>
        <span onClick={this.handleChildClick}>Click</span>
      </p>
    </div>;
  }
});

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...