如何在ReactJs中为特定组件设置数值

huangapple go评论74阅读模式
英文:

How to set a value to a specific component in ReactJs

问题

我正在尝试使用ReactJS制作一个井字棋游戏。我有一个名为setSquareValue的函数,用于将方块的值设置为X,但当我点击一个方块时,所有其他方块也都被填充为X

层次结构是Game.js -> Board.js -> Square.js。我在Game.js中使用了useState(),并且setSquareValue函数也在Game.js中。我通过Board.js将该函数传递给Square.js

以下是我的代码:
Game.js

import React, { useState } from 'react';
import './Game.css';
import Board from './Board';

const Game = () => {
  const [value, setValue] = useState(null);
  const setSquareValue = () => {
    setValue("X")
  }
  return (
    <div className='game'>
      <h1 style={{ color: "#fff" }}>Tic Tac Toe</h1>
      <h4 style={{ color: "#2D033B" }}>Winner: </h4>
      <Board value={value} setSquareValue={setSquareValue} />
    </div>
  );
};

export default Game;

Board.js

import React from "react";
import Square from "./Square";
import "./Board.css";

const Board = ({ value, setSquareValue }) => {
  const squareKeys = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  return (
    <div className="board">
      {squareKeys.map(squareKey => (
        <Square 
        key={squareKey} 
        value={value} 
        setSquareValue={setSquareValue} />
      ))}
    </div>
  );
};

export default Board;

Square.js

import React from "react";
import "./Square.css";

const Square = ({ value, setSquareValue }) => {
  return (
    <div className="square" onClick={() => setSquareValue()}>
      {value}
    </div>
  );
};

export default Square;

我希望当我点击特定方块时,只有该方块填充为X。但是每个方块都被填充为X。我该如何解决这个问题?

我已经尝试过,但是X出现在游戏的每个方块中。

英文:

I am trying to make a tic tac toe game using reactjs. I have a function named setSquareValue to set the value of squares to X but when I am clicking on a square all the other squares also filling with X.

The hierarchy is Game.js -&gt; Board.js -&gt; Square.js. I am using useState() which is in Game.js and also the function setSquareValue is in Game.js. I am passign the function to Square.js through Board.js.

Here is my codes:
Game.js

import React, { useState } from &#39;react&#39;;
import &#39;./Game.css&#39;
import Board from &#39;./Board&#39;;

const Game = () =&gt; {
  const [value, setValue] = useState(null);
  const setSquareValue = () =&gt; {
    setValue(&quot;X&quot;)
  }
  return (
    &lt;div className=&#39;game&#39;&gt;
      &lt;h1 style={{color: &quot;#fff&quot;}}&gt;Tic Tac Toe&lt;/h1&gt;
      &lt;h4 style={{color: &quot;#2D033B&quot;}}&gt;Winner: &lt;/h4&gt;
      &lt;Board value={value} setSquareValue={setSquareValue} /&gt;
    &lt;/div&gt;
  );
};

export default Game;

Board.js

import React from &quot;react&quot;;
import Square from &quot;./Square&quot;;
import &quot;./Board.css&quot;;

const Board = ({ value, setSquareValue }) =&gt; {
  const squareKeys = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  return (
    &lt;div className=&quot;board&quot;&gt;
      {squareKeys.map(squareKey =&gt; (
        &lt;Square 
        key={squareKey} 
        value={value} 
        setSquareValue={setSquareValue} /&gt;
      ))}
    &lt;/div&gt;
  );
};

export default Board;

Square.js

import React from &quot;react&quot;;
import &quot;./Square.css&quot;;

const Square = ({ value, setSquareValue }) =&gt; {
  return (
    &lt;div className=&quot;square&quot; onClick={() =&gt; setSquareValue()}&gt;
      {value}
    &lt;/div&gt;
  );
};

export default Square;

I want, when I click a certain square, only that square fill with X. But every square is filling with X. How can I solve this?

I tried but X is appearing in every box of the game.

Edited: Added CSS codes

Game.css

.game {
  background-color: #AD7BE9;
  width: 100%;
  height: 100vh;
  padding: 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

Board.css

.board {
  background-color: #645CBB;
  color: #fff;
  padding: 1rem;
  margin-top: 1rem;
  border-radius: 5px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

Square.css

.square {
  border: 1px solid #fff;
  height: 5rem;
  width: 5rem;
  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

答案1

得分: 3

以下是翻译好的部分:

"你正在将值传递给地图函数中的每个方格,为了解决这个问题,你可以将value状态和setSquareValue函数移到方格组件中,这样每个方格本身都有自己的值。

更新后的 Square.js:

import React, { useState } from "react";
import "./Square.css";

const Square = () => {
  const [value, setValue] = useState(null);
  const setSquareValue = () => {
    setValue("X")
  }
  return (
    <div className="square" onClick={setSquareValue}>
      {value}
    </div>
  );
};

export default Square;

此外,你不再需要从 Game.js 传递 valuesetSquareValue 到 Board.js 和 Square.js 中了;"

英文:

You are passing the value to every single square in your map function, for the solution you can move your value state and setSquareValue function to square component so that every square itself has its own value.

updated Square.js:

import React from &quot;react&quot;;
import &quot;./Square.css&quot;;

const Square = () =&gt; {
const [value, setValue] = useState(null);
  const setSquareValue = () =&gt; {
    setValue(&quot;X&quot;)
  }
  return (
    &lt;div className=&quot;square&quot; onClick={setSquareValue}&gt;
      {value}
    &lt;/div&gt;
  );
};

export default Square;

also you don't need to pass value and setSquareValue from Game.js to Board.js and Square.js anymore;

答案2

得分: 2

你正在为Game组件中的所有方块创建一个唯一的状态。因此,如果您随时更改任何一个方块的状态,所有方块的状态都会改变,因此会出现这个问题。所以您可以做的是,不要使用通用状态,而是在Square组件中创建一个独立的状态:

CODESANDBOX LINK

const Square = () => {
  const [value, setValue] = useState(null);
  const setSquareValue = () => {
    setValue("X");
  };
  return (
    <div className="square" onClick={setSquareValue}>
      {value}
    </div>
  );
};
英文:

You are creating a unique state for all of the square in Game component. so if you change any time all of the square state will change so this problem occurs. So what you can do is instead of common state, you can create an individual state in Square component as:

CODESANDBOX LINK

const Square = () =&gt; {
  const [value, setValue] = useState(null);
  const setSquareValue = () =&gt; {
    setValue(&quot;X&quot;);
  };
  return (
    &lt;div className=&quot;square&quot; onClick={setSquareValue}&gt;
      {value}
    &lt;/div&gt;
  );
};

答案3

得分: 1

问题出在你正在跟踪value的地方。将存储value状态的逻辑从Game.js移动到Square.js

当你的应用程序开始时,有一个Game的实例,它具有一个初始值设置为value。然后,你将这个单一的值传递给Board,在那里它被渲染了9次。同样,当你改变这个单一的值时,它在Game中也会被改变,然后传递给Board,最后被渲染9次。

Square来存储它自己的状态。

英文:

The problem is where you are tracking value. Move the logic to store the value state from Game.js to Square.js

When your app begins, there is one instance of Game which has an initial value set to value. Then you pass this single value to Board, where it renders that same value 9 times. Likewise, when you change that single value, it gets changed in Game, then passed to Board, then finally rendered 9 times.

Let Square store its own state.

答案4

得分: 0

以下是代码的翻译部分:

这是因为您只使用一个状态变量来表示所有的方块
const [value, setValue] = useState(null);

您可以声明一个长度为9的数组变量用于表示9个方块

**Game.js**


    import React, { useState } from 'react';
    import './Game.css';
    import Board from './Board';

    const Game = () => {
      const [value, setValue] = useState(Array(9).fill(''));
      const setSquareValue = (index) => {
        let values = [...value];
        values[index] = 'X';
        setValue(values);
      }
      return (
        <div className='game'>
          <h1 style={{color: "#fff"}}>Tic Tac Toe</h1>
          <h4 style={{color: "#2D033B"}}>Winner: </h4>
          <Board value={value} setSquareValue={setSquareValue} />
        </div>
      );
    };

    export default Game;


**Board.js**


    import React from "react";
    import Square from "./Square";
    import "./Board.css";

    const Board = ({ value, setSquareValue }) => {
      const squareKeys = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      return (
        <div className="board">
          {squareKeys.map((squareKey, index) => (
            <Square 
            key={squareKey} 
            value={value[index]}
            ind = {index}
            setSquareValue={setSquareValue} />
          ))}
        </div>
      );
    };

    export default Board;


**Square.js**


    import React from "react";
    import "./Square.css";

    const Square = ({ value, ind, setSquareValue }) => {
      return (
        <div className="square" onClick={() => setSquareValue(ind)}>
          {value}
        </div>
      );
    };

    export default Square;
英文:

It is because you are using only one state variable for all square:
const [value, setValue] = useState(null);

You can declare as array variable that length is 9 for 9 square.

Game.js

import React, { useState } from &#39;react&#39;;
import &#39;./Game.css&#39;
import Board from &#39;./Board&#39;;
const Game = () =&gt; {
const [value, setValue] = useState(Array(9).fill(&#39;&#39;));
const setSquareValue = (index) =&gt; {
let values = [...value];
values[index] = &#39;X&#39;;
setValue(values);
}
return (
&lt;div className=&#39;game&#39;&gt;
&lt;h1 style={{color: &quot;#fff&quot;}}&gt;Tic Tac Toe&lt;/h1&gt;
&lt;h4 style={{color: &quot;#2D033B&quot;}}&gt;Winner: &lt;/h4&gt;
&lt;Board value={value} setSquareValue={setSquareValue} /&gt;
&lt;/div&gt;
);
};
export default Game;

Board.js

import React from &quot;react&quot;;
import Square from &quot;./Square&quot;;
import &quot;./Board.css&quot;;
const Board = ({ value, setSquareValue }) =&gt; {
const squareKeys = [1, 2, 3, 4, 5, 6, 7, 8, 9];
return (
&lt;div className=&quot;board&quot;&gt;
{squareKeys.map((squareKey, index) =&gt; (
&lt;Square 
key={squareKey} 
value={value[index]}
ind = {index}
setSquareValue={setSquareValue} /&gt;
))}
&lt;/div&gt;
);
};
export default Board;

Square.js

import React from &quot;react&quot;;
import &quot;./Square.css&quot;;
const Square = ({ value, ind, setSquareValue }) =&gt; {
return (
&lt;div className=&quot;square&quot; onClick={() =&gt; setSquareValue(ind)}&gt;
{value}
&lt;/div&gt;
);
};
export default Square;

huangapple
  • 本文由 发表于 2023年2月18日 13:06:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定