当单击子元素时,同时触发父元素和子元素的onClick事件。

14
class Sample extends React.Component {
  constructor(props) {
    super(props);

    this.handleChild = this.handleChild.bind(this);
    this.handleParent = this.handleParent.bind(this);
  }

  render() {
    return (
      <div
        style={{width: '100%', height: '500px', background: 'white'}}
        onClick={this.handleParent}>

        <div
          style={{ width: '40px', height: '40px', margin: '0 auto', background: 'black'}}
          onClick={this.handleChild}>
          hello
        </div>

      </div>
    );
  }

  handleParent(e) {
    console.log('parent');
  }

  handleChild(e) {
    console.log('child');
  }
}

当子元素被点击时输出

child
parent

期望的输出为

child

我的意思是当点击子元素时,只触发子元素的onClick事件。

父元素已经正常工作。当点击父元素时,只会触发父元素的onClick事件。 问题出在子元素上。


3
在子元素的事件处理程序中使用e.stopPropagation();可以阻止父元素的事件继续传播。 - Sasikumar
1个回答

32

你需要在子处理程序中停止事件传播

handleChild(e) {
  e.stopPropagation();
  console.log('child');
}

stopPropagation - 阻止当前事件在捕获和冒泡阶段继续传播。

class Sample extends React.Component {
  constructor(props) {
    super(props);

    this.handleChild = this.handleChild.bind(this);
    this.handleParent = this.handleParent.bind(this);
  }

  render() {
    return (
      <div
        style={{width: '100%', height: '500px', background: 'white'}}
        onClick={this.handleParent}>

        <div
          style={{ width: '40px', height: '40px', margin: '0 auto', background: 'black'}}
          onClick={this.handleChild}>
          hello
        </div>

      </div>
    );
  }

  handleParent(e) {
    console.log('parent');
  }

  handleChild(e) {
    e.stopPropagation();
    console.log('child');
  }
}

ReactDOM.render(<Sample />, document.getElementById('app'));
<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="app"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接