私はそれを学ぶために反応でtic-tac-toeを実装しようとしています。しかし、私はイベントハンドラを渡すことについて真剣に混乱しています。
をSquare
に、Game
からBoard
に引き渡そうとしています。 clickHandler
が機能しますが、i
とj
は未定義のままです。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>
);
}
もちろん、それらを渡さないと定義されていません! – Li357
私が最も混乱しているのは、iとjは、実際には 'Board'の' renderSquare() 'で定義されているので、ボタンのeventHandlerに行きます。 –
'Game'コンポーネントの' handleClick'にiとjを渡す必要があります... – Li357