React,我刚开始编码,我有一个问题



我现在正在制作一个井字游戏,我想在点击另一个MyClickable对象后更改该对象的className,但我找不到方法。谢谢你的帮助。

export default class Box extends Component {
render() {
return (
<div className="box">
<MyClickable id='1' />
<MyClickable id='2' />
<MyClickable id='3' />
<MyClickable id='4' />
<MyClickable id='5' />
<MyClickable id='6' />
<MyClickable id='7' />
<MyClickable id='8' />
<MyClickable id='9' />
</div>
);
}
}
let botPlay = () => {
clickability--
}
let timeout = () => {
setTimeout(botPlay, 1500)
}
let clickability = 0
class MyClickable extends Component {
state = {
className: 'a'
}

tl;dr您需要将游戏板存储为state,并将值作为道具传递给MyClickable。然后MyClickable只查看它的value道具,例如nullXO,并根据value道具管理它自己的类名。

完整解决方案:

所以从你的州开始——它应该可以重新设置一个井字板,看起来像这样:

[
[null,null,null],
[null,null,null],
[null,null,null],
]

现在我们还需要知道该轮到谁了,所以让我们把它也添加到状态中(我们将从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——它将是nullXO:

const MyClickable = ({onClick,value}) => {
return (
<div className={value == null ? 'clickable' : 'already-clicked'} onClick={onClick}>
{value}
</div>
)
}

最新更新