React井字棋开发:点击单个方块却全部填充X的问题解决
解决React井字棋点击单个方块全部变X的问题
问题根源很明确:你现在用单个value状态变量控制所有9个方块,所有Square组件都共享同一个value值,所以只要调用setValue("X"),所有方块都会显示X。要实现点击单个方块只改对应位置,得给每个方块分配独立的状态。
修改步骤:
- Game.js:重构状态为数组,更新状态修改逻辑
把单个value改成存储9个方块值的数组,每个元素对应一个方块的初始值(默认null),同时修改setSquareValue让它接收索引,只更新对应位置的方块:
import React, { useState } from 'react'; import './Game.css' import Board from './Board'; const Game = () => { // 用数组存储9个方块的状态,初始全为null const [squares, setSquares] = useState(Array(9).fill(null)); // 接收索引参数,只修改对应位置的方块值 const setSquareValue = (index) => { // 先拷贝原数组,避免直接修改原状态(React状态不可变) const updatedSquares = [...squares]; updatedSquares[index] = "X"; setSquares(updatedSquares); } return ( <div className='game'> <h1 style={{color: "#fff"}}>Tic Tac Toe</h1> <h4 style={{color: "#2D033B"}}>Winner: </h4> {/* 把squares数组和更新函数传给Board */} <Board squares={squares} setSquareValue={setSquareValue} /> </div> ); }; export default Game;
- Board.js:传递对应位置的状态和带索引的更新函数
遍历方块时,给每个Square传递对应索引的状态值,并且绑定点击时要传递的索引(注意squareKeys是1-9,数组索引是0-8,所以要减1):
import React from "react"; import Square from "./Square"; import "./Board.css"; const Board = ({ squares, setSquareValue }) => { const squareKeys = [1, 2, 3, 4, 5, 6, 7, 8, 9]; return ( <div className="board"> {squareKeys.map(squareKey => { const index = squareKey - 1; return ( <Square key={squareKey} value={squares[index]} // 绑定当前方块的索引到点击事件 setSquareValue={() => setSquareValue(index)} /> ) })} </div> ); }; export default Board;
- Square.js:保持原样即可
Square组件只负责接收对应位置的value和点击触发的setSquareValue,不需要修改:
import React from "react"; import "./Square.css"; const Square = ({ value, setSquareValue }) => { return ( <div className="square" onClick={() => setSquareValue()}> {value} </div> ); }; export default Square;
这样修改后,每个方块都对应数组里的独立位置,点击哪个就只会更新那个位置的状态,自然只有被点击的方块显示X了。
内容的提问来源于stack exchange,提问作者Satyajit Roy
相关产品推荐
相关产品推荐

