【问题标题】:How to make access the rest of the buttons in a handleClick function如何访问 handleClick 函数中的其余按钮
【发布时间】:2022-09-26 15:58:54
【问题描述】:

我正在用 React 制作一个测验应用程序。当我单击具有正确答案的按钮时,该按钮变为绿色,这很容易实现。当用户点击错误的按钮时,按钮变为红色,但我也想让正确的答案按钮变成绿色。为了实现这一点,我需要访问其余的 button 元素

 const handleClick = async (isCorrect, e, arr) => {
        console.log(e);
        if (isCorrect) {
            setScore(score + 1)
            e.target.style.backgroundColor = \'green\'
            await delay(1500)
            e.target.style.backgroundColor = \'\'
        } else {
            e.target.style.backgroundColor = \'red\'
            await delay(1500)
            e.target.style.backgroundColor = \'\'
        }
}
const listOfAnswers = questions[questionNumber].possibleAnswers.map((q, i, arr) => {
        return (
            <Button                
                onClick={e => handleClick(q.isCorrect, e, arr)}
            >
                {q.answer}
            </Button>
        )
    })

在else 块中,我需要实现执行此操作的逻辑,但不确定如何执行。正如你所看到的,对于这个函数,我传递了arr 我正在使用map 进行迭代,但我认为这不会帮助我找到其余的button 元素。我想要的只是能够访问其余的按钮,以便我可以执行类似于e.target.style.backgroundColor = \'green\' 的操作,以向用户显示哪个答案是正确的。

任何帮助表示赞赏。谢谢

    标签: reactjs


    【解决方案1】:

    您可以为正确和不正确的类创建状态,并在需要时切换类。

    const [className, setClassName] = useState({});
    
    const handleClick = async (q, e, arr) => {
      const {isCorrect, answer} = q
      if (isCorrect) {
        setScore(score + 1);
      } 
    
      setClassName({
        [answer]: isCorrect ?'correct': "incorrect",
      });
      await delay(1500);
      setClassName({});
    };
    
    const listOfAnswers = questions[questionNumber].possibleAnswers.map(
      (q, i, arr) => {
        return (
          <Button
            onClick={(e) => handleClick(q, e, arr)}
            className={className[q.answer]}
          >
            {q.answer}
          </Button>
        );
      }
    );
    
    // Style
    .correct {
      background-color: green;
    }
    
    .incorrect {
      background-color: red;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多