【发布时间】: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