【问题标题】:Is there a way to make a tic tac toe app using React functions有没有办法使用 React 函数制作井字游戏应用程序
【发布时间】:2022-12-03 10:32:31
【问题描述】:

主要问题是当我点击棋盘内的方块时,我的井字棋盘没有更新。 似乎是 useState 函数; setXIsNext 正在工作。但我不知道 setGame 功能是否有效。

我试图删除切片功能,但它仍然没有更新。 我试着把

dupGame[i] = xIsNext ? 'X' : 'O'

进入 setGame 函数,它更新了棋盘中的第一个方块,而不是被点击的方块。

使用的代码:

import { useState } from 'react'
import './tiktacktoe.css'
function Square(props) {
    return (
        <div className="square" onClick={props.onClick}>
            {props.value}
        </div>
    )
}
function Board(){
    const [game, setGame] = useState(Array(9).fill(null))
    const [xIsNext, setXIsNext] = useState(true)
    
    function handleClick(i) {
        const dupGame = game.slice()
        if (dupGame[i]) {
            return
        }
        dupGame[i] = xIsNext ? 'X' : 'O'
        setXIsNext(!xIsNext)
        setGame(dupGame)
    }
    function renderSquare(i){
        return (
            <Square value={game[i]} onClick={handleClick} id={i} />
        )
    }
    
    let board = []
    for (let i = 0; i < 9; i++) {
        board.push(renderSquare(i))
    }
    let status = "Next player: " + (xIsNext ? 'X' : 'O')
    return (
        <div >
            <div>
                {status}
            </div>
            <div className='board'>
                {board}
            </div>
        </div>
    )
}
export function TikTackToe() {
    
    return (
        <div>
            <Board/>
        </div>
    )
}

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    你的 onclick 函数是错误的,当调用事件传递给函数时。

    尝试

    <Square value={game[i]} onClick={() => handleClick(i)} id={i} />
    

    或更改 handleClick 为

    function handleClick(e) {
            const i = e.target.value;
            const dupGame = game.slice()
            if (dupGame[i]) {
                return
            }
            dupGame[i] = xIsNext ? 'X' : 'O'
            setXIsNext(!xIsNext)
            setGame(dupGame)
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      相关资源
      最近更新 更多