我想实现一个功能的React井字游戏说,在新的React测试版文档网站。该功能是突出显示获胜的方块在董事会上,如果一个球员赢了。经过努力编写代码和调试,以找出问题,我仍然不明白为什么它是行不通的。检查凯文王的文章中的一个类似的问题,但他的方法似乎不适用于我的情况。
刚开始学习React tho,并希望确保我完成这个功能和一些更多,并了解React以及在移动到使更多的项目。
下面是Codepen上代码的链接
代码有点庞大,但我仍然会在这里显示主要组件。
function Square({value, onSquareClick, isWinning}) {
return (
<button
className={"square " + (isWinning ? "winning-square" : null)} onClick={onSquareClick}>
{value}
</button>
);
}
function Board({xIsNext, squares, onPlay, winningSquares}) {
function handleClick(i) {
if (squares[i] || calculateWinner(squares)) {
return;
}
const nextSquares = squares.slice();
if (xIsNext) {
nextSquares[i] = "X";
}
else {
nextSquares[i] = "O";
}
onPlay(nextSquares);
}
var winner = calculateWinner(squares);
let status;
let winnerName = winner;
if (winner) {
status = " is the winner! " + "at line " + winner.line;
console.log(winner.line);
}
else {
status = "Next Player - " + (xIsNext ? "X" : "O");
}
// A dirty trick to do make the Board component render squares in less lines of code.
// Originally supposed to be
const row = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
];
return (
<>
<div className="status">
<span className="winner-name">{winnerName}</span>
<span className="status-desc">{status}</span>
</div>
<div className="board-row">
{row[0].map((index) => <Square value={squares[index]} onSquareClick={() => handleClick(index)} key={index} isWinning={winningSquares.includes(index)} />)}
</div>
<div className="board-row">
{row[1].map((index) => <Square value={squares[index]} onSquareClick={() => handleClick(index)} key={index}isWinning={winningSquares.includes(index)} />)}
</div>
<div className="board-row">
{row[2].map((index) => <Square value={squares[index]} onSquareClick={() => handleClick(index)} key={index} isWinning={winningSquares.includes(index)} />)}
</div>
{/*
Changed code below to make it more efficient, cleaner and not hardcoded according to the instruction on the React Framework docs page.
<div className="board-row">
<Square value={squares[0]} onSquareClick={() => handleClick(0)} />
<Square value={squares[1]} onSquareClick={() => handleClick(1)} />
<Square value={squares[2]} onSquareClick={() => handleClick(2)} />
</div>
<div className="board-row">
<Square value={squares[3]} onSquareClick={() => handleClick(3)} />
<Square value={squares[4]} onSquareClick={() => handleClick(4)} />
<Square value={squares[5]} onSquareClick={() => handleClick(5)} />
</div>
<div className="board-row">
<Square value={squares[6]} onSquareClick={() => handleClick(6)} />
<Square value={squares[7]} onSquareClick={() => handleClick(7)} />
<Square value={squares[8]} onSquareClick={() => handleClick(8)} />
</div> */}
</>
);
}
// Main logic of the game.
// Stores state in the history and also renders the Board component.
export default function Game() {
const [history, setHistory] = useState([Array(9).fill(null)]);
const [currentMove, setCurrentMove] = useState(0);
const xIsNext = currentMove % 2 === 0;
const currentSquares = history[currentMove];
function handlePlay(nextSquares) {
const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
setHistory(nextHistory);
setCurrentMove(nextHistory.length - 1);
}
// function jumpTo(nextMove) {
// setCurrentMove(nextMove);
// }
const moves = history.map((squares, move) => {
let description;
if (move > 0) {
description = "Move #" + move;
}
else {
description = "You've made no moves.";
}
return (
<li key={move}>
{description}
</li>
)
});
// Sets the state of the toggle ascending or descending mode of the game moves.
const [toggleUp, setToggleUp] = useState(true);
// Function tracks the click and updates state accordingly.
function changeGameMoves() {
if (toggleUp) {
setToggleUp(true);
}
setToggleUp(!toggleUp);
}
return (
<>
<div className="game">
<div className="game-board">
<Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} winningSquares={winner ? winner.line : []}/>
</div>
<div className="game-info">
<button className="toggle-btn" onClick={changeGameMoves}>
Toggle Game Moves
</button>
<h2>Game Moves</h2>
<ul id="game-moves">
{toggleUp ? moves.reverse() : moves}
</ul>
</div>
</div>
</>
)
}
function calculateWinner(squares) {
// These are lines checking for whether the player has played on the indicated lines signifying a win.
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
// Assigns the values of each line array to a, b and c respectively;
// i.e. for line 1 which is index 0 in the lines array,
// a = 0, b = 1, c = 2
// After looping, it checks if the value of a, b and c are the same and returns the value of variable a and the line which made the win.
for (let i = 0; i < lines.length; i++) {
var [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return {
player: squares[a],
line: [a, b, c],
};
}
}
return null;
}
我试着写一个自定义的解决方案,但没有得到预期的结果,我上网查了查,发现了一个article详细说明如何解决的挑战,但这篇文章是基于旧的React方式的组件使用类。通读代码理解,并试图将相同的过程应用到我自己的代码,但最终遇到了障碍。
该代码应该改变三个方块的背景颜色,使游戏中的胜利。
1条答案
按热度按时间eit6fx6z1#
您面临的问题是
calculateWinner
函数返回null
或{ player: "O", line: [0, 3, 4] }
形式的JSON,您需要使用optional chaining operator(?.
)处理空情况。替换:
与:
每个地方都能解决这个问题。
检查工作演示: