如何解决Winning Square井字游戏ReactJs
class Game extends Component {
constructor(props)
{
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null),},],xIsNext: true,stepNo: 0,};
}
handleClick(i)
{
const history = this.state.history.slice(0,this.state.stepNo + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? "X" : "O";
this.setState({
history: history.concat([
{
squares: squares,]),stepNo : history.length,xIsNext: !this.state.xIsNext,});
}
jumpTo(step) {
this.setState({
stepNo : step,xIsNext: (step % 2) === 0
})
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step,move) => {
const decs = move ? "DESC: go to move # " + move :
"DESC: go to the game start";
return (
<li key={move}>
<button
className = "focus-buttons"
onClick={() => this.jumpTo(move)}
>{decs}</button>
</li>
);
});
let status;
if (winner) {
status = "Winner: " + winner;
} else if ((this.state.xIsNext ? "X" : "O")){
status = "Next player: " + (this.state.xIsNext ? "X" : "O")}
return (
<div>
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
{status}
{moves}
</div>
);
}
}
function calculateWinner(squares){
const lines =[
[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,7],[2,5,];
for
(let i = 0; i < lines.length; i++) {
const [a,b,c] = lines[i];
if ( squares [a] && squares [a] === squares [b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;}
在上面的部分中,我想以某种方式对获胜的正方形进行样式设置,但无法访问那些正方形。如何捕获那些动态获胜平方,以便可以突出显示它们以显示“ x”或“ o”的获胜平方?我尝试使用不同的方法,但是通常最终会设计整个正方形的样式,而不是必需的样式?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。