这里的学习反应,并在此进行中-tac-toe intro:https://react.dev/learn/tutorial-tic-tac-toe
。
我试图理解为什么我的法典没有发挥作用。 https://react.dev/learn/tutorial-tac-toe#completing-the-MO 部分,请添加如下内容:
<Square value={squares[8]} onSquareClick={() => handleClick(8)} />
I m trying to take a slightly different approach and create the squares programmatically, like so:
export default function Board() {
const [squares, setSquares] = useState(Array(9).fill(null));
function handleClick(i) {
const nextSquares = squares.slice();
nextSquares[i] = "X";
setSquares(nextSquares);
}
var boardRows = [];
var counter = 0;
for (var i = 0; i < 3; i++) {
var boardSquares = [];
for (var j = 0; j < 3; j++) {
boardSquares.push(<Square value={squares[counter]} onSquareClick={() => handleClick(i)} />);
counter ++;
}
boardRows.push(<div className="board-row"> {boardSquares} </div>);
}
return boardRows;
}
The problem is, the handleClick(i)
is using 9, since that s the final value of my counter. Is there a way to have the function "save" the value that will be passed in on the click? Or am I going about this wrong?