我正在使用React Hook构建一个TicTacToe。当TicTacToe工作正常时,按钮却在点击时改变了位置。图片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>
这里的问题是,你正在渲染三行正方形,并且没有给行分配任何宽度或高度。我能够解决这个问题,使行的显示为柔性。
你可以检查这里的代码。CodeSandbox