老师点击效果不出来啊
import { useState } from 'react';
import Square from './square';
function Board() {
const [squares, setSquares] = useState(Array(9).fill(null))
const status = 'status'
const clickHandler = (index) => {
// 当发生点击之后,把当前点击的格子存入常量
const currentSquare = squares[index];
// 当前格子没有被点击则向下执行
if (!currentSquare) {
// 在squares中过滤查找
const filledSquares = squares.filter(item => (item === "x" || item === "0"));
// 如果已经有X那么下一个就是0
const filledNumber = filledSquares.length;
// 如果有0则下一个是x
const nextLetter = (filledNumber % 2 === 0) ? "x" : "0";
// 创建一个新的squares(新数组)
const newSquares = squares.slice();
// 将下一个X或者是0存入新数组中的index对应的一项中去
newSquares[index] = nextLetter;
// 最后更新数组,这样视图才能更新
setSquares(newSquares);
}
// squares[index] = "x"
// setSquares(squares)
}
return (
<>
<div>{status}</div>
<div className="boare-row">
<Square value={squares[0]} index={0} onClick={clickHandler} />
<Square value={squares[1]} index={1} onClick={clickHandler} />
<Square value={squares[2]} index={2} onClick={clickHandler} />
</div>
<div className="boare-row">
<Square value={squares[3]} index={3} onClick={clickHandler} />
<Square value={squares[4]} index={4} onClick={clickHandler} />
<Square value={squares[5]} index={5} onClick={clickHandler} />
</div>
<div className="boare-row">
<Square value={squares[6]} index={6} onClick={clickHandler} />
<Square value={squares[7]} index={7} onClick={clickHandler} />
<Square value={squares[8]} index={8} onClick={clickHandler} />
</div>
</>
)
}
export default Board;
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星