React - Prevent Event Trigger on Parent From Child

前端 未结 3 1259
眼角桃花
眼角桃花 2021-02-01 00:52

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, t

相关标签:
3条回答
  • 2021-02-01 01:10

    I wanted to invoke function on props but at the same time wanted to stop event propagation from child to parent, here is how its handled

    class LabelCancelable extends Component {
    
      handleChildClick(e) {
        e.stopPropagation()
      }
      closeClicked(e, props) {
        e.stopPropagation();
        props.onCloseClicked()
      }
    
      render() {
        const {displayLabel} = this.props;
        return (
          <span className={ "label-wrapper d-inline-block pr-2 pl-2 mr-2 mb-2" } onClick={ this.handleChildClick }>
              <button type="button" className="close cursor-pointer ml-2 float-right" aria-label="Close"
                  onClick={(e) => this.closeClicked(e, this.props) }>
                  <span aria-hidden="true">&times;</span>
              </button>
              <span className="label-text fs-12">
                { displayLabel }
              </span>
          </span>
        );
      }
    }
    
    export default LabelCancelable;
    
    0 讨论(0)
  • 2021-02-01 01:14

    Another solution is to attach to the event callback on the parent the following:

    if(event.target == event.currentTarget){
      event.stopPropagation()
      ....
    }
    

    This way you can intercept events, that originated in the attached DOM node and unrelated events are relayed to the next node.

    0 讨论(0)
  • 2021-02-01 01:27

    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>

    0 讨论(0)
提交回复
热议问题