tl;dr 您需要将游戏板存储为状态并将值作为道具传递给MyClickable。然后MyClickable 只是看看它是value 道具 - 例如null、X 或 O - 它根据 value 属性管理自己的类名。
完整解决方案:
所以从你的状态开始 - 它应该类似于井字棋盘,看起来像这样:
[
[null,null,null],
[null,null,null],
[null,null,null],
]
现在我们还需要知道轮到谁了,所以我们也将其添加到 state(我们将从 X 开始)
{
playerTurn: 'X',
board: [
[null,null,null],
[null,null,null],
[null,null,null],
]
}
太好了,现在我们知道我们的状态应该是什么样子了,让我们来制作组件:
expport class Board extends React.Component = {
constructor() {
this.state = {
playerTurn: 'X',
board: [
[null,null,null],
[null,null,null],
[null,null,null],
]
}
}
// when this is called, we update our board state and we change the player turn from X to O (or vice versa)
handleClick = (row,col) => {
// number 1 rule of React - don't mutate state (or props, or anything really)
const nextBoard = [...this.state.board];
// change the next turn to X, or O, depending on whose turn it is currently
const nextTurn = this.state.playerTurn === 'X' ? 'O': 'X';
// set the value of the board at row/col to X or O, depending on whose turn it is currently
nextBoard[row][col] = this.state.playerTurn;
// at this point you can determine if the game is over or not
this.setState({playerTurn:nextTurn,board:nextBoard});
}
// helper - tells us if the game is over
winner = () => {
// return X if X has one, based on the state, or O is O has won, or null if nobody has won
// leave this up to you to implement
}
render() {
// if we have a winner, we can show who won!
const winner = this.winner();
if(winner) {
return <div>{winner} won!</div>
}
// if we don't have a winner, show the game board
return (
<div className="box">
{
this.state.board.map((row,i) =>
row.map((value,m) => (
<MyClickable
// if this already has a value, pass undefined as `onClick`
onClick={value ? undefined : () => this.handleClick(i,m)}
value={value}
/>
))
)
}
</div>
)
}
}
然后你有MyClickable,类似这样的东西(我们将制作一个简单的函数组件,因为它没有任何状态)
const MyClickable = ({onClick,value}) => {
return (
<div onClick={onClick}>
{value}
</div>
)
}
如果你想改变MyClickable组件渲染的div的类名,你需要做的就是查看value——它要么是null,要么是X,要么是O:
const MyClickable = ({onClick,value}) => {
return (
<div className={value == null ? 'clickable' : 'already-clicked'} onClick={onClick}>
{value}
</div>
)
}