gpt4 book ai didi

javascript - 为什么 Button 组件在单击时改变位置?

转载 作者:行者123 更新时间:2023-12-03 14:10:24 25 4
gpt4 key购买 nike

我正在使用 React Hook 构建 TicTacToe。虽然 TicTacToe 工作正常,但按钮在单击时会改变位置。图1是初始游戏板,图2是点击按钮后的样子!它正在下降。如果我连续单击三个按钮,它将转到上一个位置(图 3)。我希望按钮在玩家点击时不改变位置

image link here

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

关于javascript - 为什么 Button 组件在单击时改变位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61676815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com