将状态更改应用于 React 中数组的特定索引

Applying state change to specific index of an array in React

你好!带着菜鸟问题再次回到它!

所以我正在从 API 中获取数据以呈现测验应用程序,并且我正在努力使用一个简单的(我认为)函数: 我有一个包含 4 个答案的数组。这个数组呈现 4 divs(所以我的每个答案都可以有一个 individual div)。我想更改点击的 div 的颜色,以便稍后验证点击的 div 是否是好的答案。

问题是当我点击时,整个答案数组(4 divs)都在改变颜色。

我怎样才能做到这一点?

我对正在渲染的 divs 做了类似的事情:

const [on, setOn] = React.useState(false);

  function toggle() {
    setOn((prevOn) => !prevOn);
  }

  const styles = {
    backgroundColor: on ? "#D6DBF5" : "transparent",
  };

我将在 post 末尾提供组件的完整代码和 API link,因此如果需要,您可以看到我是如何渲染的整个事情。

可能是因为 API 的对象缺少“on”值?我试图为每个项目分配一个布尔值,但我似乎无法让它工作。

在此先感谢您的帮助!

整个组件:

import React from "react";
import { useRef } from "react";

export default function Quizz(props) {
  const [on, setOn] = React.useState(false);

  function toggle() {
    setOn((prevOn) => !prevOn);
  }

  const styles = {
    backgroundColor: on ? "#D6DBF5" : "transparent",
  };

  function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      let j = Math.floor(Math.random() * (i + 1));
      let temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  let answers = props.incorrect_answers;

  const ref = useRef(false);
  if (!ref.current) {
    answers.push(props.correct_answer);

    shuffleArray(answers);
    ref.current = true;
  }

  const cards = answers.map((answer, key) => (
    <div key={key} className="individuals" onClick={toggle} style={styles}>
      {answer}
    </div>
  ));

  console.log(answers);
  console.log(props.correct_answer);

  return (
    <div className="questions">
      <div>
        <h2>{props.question}</h2>
      </div>
      <div className="individuals__container">{cards}</div>
      <hr />
    </div>
  );
}

我正在使用的API link:“https://opentdb.com/api.php?amount=5&category=27&type=multiple”

由于您的答案在每个测验中都是唯一的,您可以将它们用作 id,而不是在状态中保留 boolean 值,您可以在状态中保留所选答案,当你想渲染你的 JSX 时,你可以检查状态是否与当前答案相同,如果是,那么你可以像这样更改它的背景:

function Quizz(props) {
  const [activeAnswer, setActiveAnswer] = React.useState('');
  function toggle(answer) {
    setActiveAnswer(answer);
  }
  ...
  const cards = answers.map((answer, key) => (
    <div key={key}
         className="individuals"
         onClick={()=> toggle(answer)}
         style={{background: answer == activeAnswer ? "#D6DBF5" : "transparent" }}>
         {answer}
    </div>
));
  ...
}