这是我到目前为止的代码,通过遵循官方的react js教程来制作一款tic-tac-toe游戏,我能够完成游戏,但struct在第一个挑战中使用循环创建正方形而不是硬编码它,正如你可以看到代码的注释部分.

import { useState } from "react";

function Square({ value, onSquareClick }) {
    return (
        <button className="square" onClick={onSquareClick} >{value}</button>
    );
}

function CreateSquares(squares, handleClick) {

    const data = [];
    for (let i = 0; i < 3; i++) {
        const rows = [];
        for (let j = 0; j < 3; j++) {
            rows.push(
                <Square value={squares[j]} onSquareClick={() => handleClick(j)} key={j} />
            );
        }
        data.push(
            <div className="board-row" key={i}>{rows}</div>
        );
    }
    return data;
}

function Board({ xIsNext, squares, onPlay }) {

    let winner = calculateWinner(squares);

    function handleClick(index) {
        if (squares[index] || winner) {
            return;
        }
        const nextSquares = squares.slice();

        nextSquares[index] = xIsNext ? 'X' : 'O';

        onPlay(nextSquares);
    }
    let status = winner ? "Winner: " + winner : "Next Player: " + (xIsNext ? "X" : "O");

    return (
        <>
            <div className="status">{status}</div>
            <CreateSquares squares={squares} handleClick={handleClick} />
            {/* <div className="board-row">
                <Square value={squares[0]} onSquareClick={() => handleClick(0)} />
                <Square value={squares[1]} onSquareClick={() => handleClick(1)} />
                <Square value={squares[2]} onSquareClick={() => handleClick(2)} />
            </div>
            <div className="board-row">
                <Square value={squares[3]} onSquareClick={() => handleClick(3)} />
                <Square value={squares[4]} onSquareClick={() => handleClick(4)} />
                <Square value={squares[5]} onSquareClick={() => handleClick(5)} />
            </div>
            <div className="board-row">
                <Square value={squares[6]} onSquareClick={() => handleClick(6)} />
                <Square value={squares[7]} onSquareClick={() => handleClick(7)} />
                <Square value={squares[8]} onSquareClick={() => handleClick(8)} />
            </div> */}
        </>
    );
}

export default function Game() {
    const [history, setHistory] = useState([Array(9).fill(null)]);
    const [currentMove, setCurrentMove] = useState(0);
    const xIsNext = currentMove % 2 === 0;
    const currentSquares = history[currentMove];

    function handlePlay(nextSquares) {
        const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
        setHistory(nextHistory);
        setCurrentMove(nextHistory.length - 1);
    }

    function jumpTo(nextMove) {
        setCurrentMove(nextMove);
    }

    const moves = history.map((squares, move) => {
        let description = move > 0 ? 'Go to move #' + move : "Go to game start";

        return (
            <li key={move}>
                <button onClick={() => { jumpTo(move) }}>{description}</button>
            </li>
        );
    });

    return (
        <div className="game">
            <div className="game-board">
                <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
            </div>
            <div className="game-info">
                <ol>{moves}</ol>
            </div>
        </div>
    );
}

function calculateWinner(squares) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];

    let len = lines.length;
    for (let i = 0; i < len; i++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return squares[a];
        }
    }

    return null;
}

这就是我收到的错误,我不知道如何修复它.

    handleClick is not a function
    TypeError: handleClick is not a function
    at onSquareClick (http://localhost:3000/main.9d076070d9e17e2c1932.hot-update.js:51:30)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:10826:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:10870:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:10927:35)
    at invokeGuardedCallbackAndCatchFirstError (http://localhost:3000/static/js/bundle.js:10941:29)
    at executeDispatch (http://localhost:3000/static/js/bundle.js:15085:7)
    at processDispatchQueueItemsInOrder (http://localhost:3000/static/js/bundle.js:15111:11)
    at processDispatchQueue (http://localhost:3000/static/js/bundle.js:15122:9)
    at dispatchEventsForPlugins (http://localhost:3000/static/js/bundle.js:15131:7)
    at http://localhost:3000/static/js/bundle.js:15291:16

我试着在这里学习react 和 struct ,我已经学习了官方快速入门指南2-3次,但仍然不能找出我做错了什么,任何帮助都将不胜感激

推荐答案

使其发挥作用,以下是有效的解决方案

import { useState } from "react";

function Square({ value, onSquareClick }) {
    return (
        <button className="square" onClick={onSquareClick} >{value}</button>
    );
}

function CreateSquares({ squares, checkClick }) {

    const data = [];
    for (let i = 0; i < 3; i++) {
        const rows = [];
        for (let j = 0; j < 3; j++) {

            const index = i * 3 + j; // Calculate a unique index for each square

            rows.push(
                <Square value={squares[index]} onSquareClick={() => checkClick(index)} key={index} />
            );
        }
        data.push(
            <div className="board-row" key={i}>{rows}</div>
        );
    }
    return data;
}

function Board({ xIsNext, squares, onPlay }) {

    let winner = calculateWinner(squares);

    function handleClick(index) {

        if (squares[index] || winner) {
            return;
        }
        const nextSquares = squares.slice();

        nextSquares[index] = xIsNext ? 'X' : 'O';

        onPlay(nextSquares);
    }
    let status = winner ? "Winner: " + winner : "Next Player: " + (xIsNext ? "X" : "O");

    return (
        <>
            <div className="status">{status}</div>
            <CreateSquares squares={squares} checkClick={handleClick} />
        </>
    );
}

export default function Game() {
    const [history, setHistory] = useState([Array(9).fill(null)]);
    const [currentMove, setCurrentMove] = useState(0);
    const xIsNext = currentMove % 2 === 0;
    const currentSquares = history[currentMove];

    function handlePlay(nextSquares) {
        const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
        setHistory(nextHistory);
        setCurrentMove(nextHistory.length - 1);
    }

    function jumpTo(nextMove) {
        setCurrentMove(nextMove);
    }

    const moves = history.map((squares, move) => {
        let description = move > 0 ? 'Go to move #' + move : "Go to game start";

        return (
            <li key={move}>
                <button onClick={() => { jumpTo(move) }}>{description}</button>
            </li>
        );
    });

    return (
        <div className="game">
            <div className="game-board">
                <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
            </div>
            <div className="game-info">
                <ol>{moves}</ol>
            </div>
        </div>
    );
}

function calculateWinner(squares) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];

    let len = lines.length;
    for (let i = 0; i < len; i++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return squares[a];
        }
    }

    return null;
}

我需要通过考试

<CreateSquares squares={squares} checkClick={handleClick} />

并且需要这样做

function CreateSquares({ squares, checkClick }) {

而不是这个

function CreateSquares( squares, checkClick ) {

Reactjs相关问答推荐

Shadck/ui Select -当用户 Select 项目时更改状态

是否将样式应用于父悬停(框架运动)上的子元素?

使用REACT-RUTER-DOM链接仅更新一个搜索参数

获取更改后的状态值

在React中映射对象数组时,如何正确呈现JSX.Element或React.ReactNode类型?

是否为Reaction中未使用的组件生成Tailwincss样式?

使用experial_useFormState将参数传递给服务器操作

React 错误无法读取未定义的属性(读取id)#react

将 useRef 与 useImperativeHandle 一起使用时,React 不会重新渲染

useState数组不更新

cypress `cy.now()` Type 'Promise' 没有调用签名

使用 MuiCssBaseline 在所有 MUI v5 标签上设置边距 0

我收到Uncaught TypeError: props.handleSelect is not a function

带有 webpack 错误多个文件匹配路由名称的 Expo-router.无法Bundle 或部署应用程序

当每个元素都可拖动时,移动设备上的滚动列表出现问题

导入样式化组件时未导入组件内容

作为单个变量的 React 组件是否比 memoized 组件渲染得更快?

单元测试 useLoaderData() react-router v6 加载器函数

理解 React 中的 PrevState

Lodash 在命名导入中导入整个包