我正在使用React Hook构建一个井字棋游戏。虽然井字棋游戏运行良好,但是在单击按钮时,按钮位置会发生改变。图1是初始游戏板,图2是单击按钮后的情况!它向下移动。如果我连续点击三个按钮,它就会回到先前的位置(图3)。
我希望玩家单击按钮时不改变按钮位置
import React, {useState} from 'react';
function Square (props){
return(
<button className = "button" onClick = {props.onClick}>
{props.value}
</button>
);
}
function Board(){
//state
const [boardSquares, setBoardSquares] = useState(Array(9).fill(null));
const [xIsNext, setXIsNext] = useState(true);
const handleClick = index =>{
const squares = [...boardSquares];
if( whoIsTheWinner(boardSquares) || squares[index]) return; // if this already has a value return
//add X or O
squares[index] = xIsNext ? "X" : "O";
//calculate next turn
//set the state of the board
setBoardSquares(squares);
//set the state of the turn
setXIsNext(!xIsNext);
};
//create a render square function
//takes an index and return a square with correct value and function
const renderSquare = (index) => {
return <Square value={boardSquares[index]} onClick={()=>handleClick(index)}/>
};
//create the board
//calculates winner
let status ;
const winner = whoIsTheWinner(boardSquares);
status = winner ?
`Winner is: ${winner}` :
`Next player: ${xIsNext ? "X" : "O"}`;
function whoIsTheWinner(squares){
const winningLine = [
[0, 1, 2],
[0, 3, 6],
[0, 4, 8],
[1, 4, 7],
[2, 5, 8],
[3, 4, 5],
[6, 7, 8],
[0, 4, 8]
];
console.log(winningLine)
for (let i=0; i < winningLine.length; i++){
const [a,b,c]=winningLine[i];
if (squares[a] && squares[a] === squares[b] && squares[b]===squares[c])
return squares[a];
}
return null;
};
return(
<div>
<div>
{/* who's turn is it? */}
{status}
</div>
{/* this div below is one row */}
<div>
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div>
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div>
{renderSquare(6)}
{renderSquare(7)}
{renderSquare(8)}
</div>
</div>
);
}
export default Board;
.button{
width: 150px;
height: 150px;
background-color: greenyellow;
margin: 0;
padding: 0;
}
.button:active{
background-color: grey;
}
.button:hover{
background-color: palegreen;
}
.refresh{
background-image: url("../src/image/refresh.jpg");
background-color: transparent;
background-repeat: no-repeat;
width: 41px;
height: 41px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>