在单击子节点时触发子节点和父节点的onClick

onClick of both child and parent triggered when child is clicked

本文关键字:子节点 父节点 onClick 单击      更新时间:2023-09-26
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当孩子被点击。

父端工作正常。当parent被点击时,它只会触发parent的onClick。我的问题是孩子。

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

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>