你如何停止在ReactJS中的传播

时间:2017-11-03 19:21:34

标签: javascript reactjs stoppropagation

有人可以帮助解释如何停止点击事件传播吗?我已经阅读了很多其他帖子,但我仍然无法弄清楚。

我有一个40x50盒子的网格,当我点击一个盒子时,我想看看那个盒子的ID。目前,当我点击它时会冒泡并返回Board,因为它已被点击。所以我需要停止传播,对吗?我在哪里/怎么做?我尝试在i.stopPropagation();方法中传递handleClick(),但它告诉我i.stopPropagation();不是函数。

function Square(props) {
  return (
    <div className="square" id={props.id} onClick={props.onClick}/>
  );
}

class Board extends Component {
  rowsByColumns(rows, columns) {
    let arr=[];
    let k=0;
    let m=0
    for (let i=0;i<rows;i++) {
      arr.push([])
      for (let j=0;j<columns;j++) {
        arr[i].push(<Square key={"square"+m++} id={"square"+m} living={false} onClick={() => this.props.onClick(this)}/>)
      }
    }
    let newArr = arr.map(row => <Row key={"row"+k++}>{row}</Row>);
    return (newArr);
  }

  render() {
    return (
        <div id="board">
          {this.rowsByColumns(40,50)}
        </div>
    );
  }
}

class App extends Component {
  constructor() {
    super();
    this.state = {
      alive: ["square1"],
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(i) {
    console.log(i);
    this.setState({
      alive: this.state.alive.concat([i])
    })
  }

  render() {
    return (
      <div className="App container-fluid">
        <main className="row justify-content-center">
          <Board alive={this.state.alive} onClick={i => this.handleClick()}/>
          </div>
        </main>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您的点击处理程序会收到一个事件对象。在其上使用stopPropagation

handleClick(e) {
    e.stopPropagation();
}

然后在onClick

onClick={this.handleClick}

实例 - 孩子在其看到的每次点击停止时停止:

class Parent extends React.Component {
  constructor(...args) {
    super(...args);
    this.handleClick = () => {
      console.log("Parent got the click");
    };
  }
  render() {
    return <div onClick={this.handleClick}>
      Click here to see parent handle it.
      <Child />
      </div>;
  }
}
class Child extends React.Component {
  constructor(...args) {
    super(...args);
    this.stopClick = true;
    this.handleClick = e => {
      if (this.stopClick) {
        e.stopPropagation();
        console.log("Child got the click and stopped it");
      } else {
        console.log("Child got the click and didn't stop it");
      }
      this.stopClick = !this.stopClick;
    };
  }
  render() {
    return <div onClick={this.handleClick}>I'm the child</div>;
  }
}

ReactDOM.render(
  <Parent />,
  document.getElementById("root")
);
<div id="root"></div><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>