2017-01-22 3 views
-1

私はそれを学ぶために反応でtic-tac-toeを実装しようとしています。しかし、私はイベントハンドラを渡すことについて真剣に混乱しています。
​​をSquareに、GameからBoardに引き渡そうとしています。 clickHandlerが機能しますが、ijは未定義のままです。Reactでイベントハンドラをpropsとして渡します。

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> 
    ); 
    } 
+0

もちろん、それらを渡さないと定義されていません! – Li357

+0

私が最も混乱しているのは、iとjは、実際には 'Board'の' renderSquare() 'で定義されているので、ボタンのeventHandlerに行きます。 –

+0

'Game'コンポーネントの' handleClick'にiとjを渡す必要があります... – Li357

答えて

0

それはおそらくあなたが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) }/>; 

にiとjを渡していない、とは何の関係も反応していません handleClick = {( i、j)=>

私は実際にclickイベントですが、引数iとjに名前を付けたので、あなたはiとjをシャドーイングしてSquareに渡しています。 handleClickの引数を省略すると、iとjは外側のスコープからキャプチャされます

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

が役に立ちます。ありがとうございます –

+0

'handleClick = {this.props.handleClick}'? – Madbreaks

関連する問題