在React中将事件处理程序作为道具传递。

时间:2017-01-22 21:28:24

标签: javascript reactjs event-handling jsx

我正在努力实施tic-tac-toe做出反应来学习它。但是,我对传递事件处理程序感到非常困惑 我试图将handleClickSquare传递给GameBoardclickHandler有效,但ij仍未定义。

class Game extends Component {
      constructor() {
        super();
        this.state = {squares: Array(3).fill(Array(3).fill(null))};
      }
      render() {
        return(
          <div className="game">
            <p> STATUS </p>
            <Board squares={this.state.squares} handleClick={(i,j) => this.handleClick()}/>
          </div>
        )
      }
      handleClick(i,j) {
         console.log(i);
         console.log(j);
      }
    }

    class Board extends Component {
      constructor() {
        super();
      }
      renderSquare(i,j) {
        return <Square value={this.props.squares[i][j]} handleClick={ (i,j)=> this.props.handleClick(i,j) }/>;
      }
      render() {
        const board = this.props.squares.map((row,i) =>row.map((j,k)=> this.renderSquare(i,k)));
        return(
          <div className="board">
            {board}
          </div>
        );
      }

    }
    function Square(props) {
      return(
        <button className="square" onClick={(i,j) => props.handleClick()}>

        </button>
      );
    }

1 个答案:

答案 0 :(得分:0)

它可能与反应无关,你没有将i和j传递给handleClick

(i,j) => this.handleClick()

<Board squares={this.state.squares} handleClick={(i,j) => this.handleClick()}/>

也在这里

<Square value={this.props.squares[i][j]} handleClick={ (i,j)=> this.props.handleClick(i,j) }/>;

在     handleClick = {(i,j)=&gt;

我实际上是点击事件,但是因为你命名参数i和j你正在影子我和j传递给Square。如果在handleClick中省略参数,则将从外部范围中捕获i和j

 <Square value={this.props.squares[i][j]} handleClick={ () => this.props.handleClick(i,j) }/>;