我有一个带有问题属性的对象。问题是一个由13个objects.Each对象组成的数组,它有一个包含2-4个对象的选项数组,并且每个对象都有一个isCorrect属性,该属性要么为真,要么为空。

我所有的问题都会被呈现出来。我有一个按钮,我想要为用户选择的每个正确答案添加一个类名。你们对我如何实现这一点有什么建议吗?
{quiz.questions.map((question, index) => (
<ContentWrapper key={question._key}>
<h3>
{`${index + 1}. `}
{question.title}
</h3>
{question.choices.map(choice => (
<ChoiceStyle id={"wrapper" + choice._key} key={choice._key}>
<input
type="radio"
id={choice._key}
name={question._key}
onChange={updateScore}
value={choice.isCorrect === null ? "0" : "1"}
/>
<label htmlFor={choice._key}>{choice.title}</label>
</ChoiceStyle>
))}
<ButtonComponent
type="button"
buttonType="second"
title="Sjekk svar"
onClick={() => {
calculateScore();
}}
/>那个按钮只是计算分数,但我可能需要在这个按钮上添加另一个函数?我也在使用带样式的组件
发布于 2021-02-03 20:56:29
有多种方法可以做到这一点,最简单、侵入性最小的方法是添加一个三元条件,根据isCorrect属性显示/隐藏类名。
我假设quiz是在每个onChange中更改的状态,以刷新测验中的所有实时更改。此时:
{quiz.questions.map((question, index) => (
<ContentWrapper key={question._key}>
<h3>
{`${index + 1}. `}
{question.title}
</h3>
{question.choices.map(choice => (
<ChoiceStyle id={"wrapper" + choice._key} key={choice._key}>
<input
type="radio"
id={choice._key}
name={question._key}
onChange={updateScore}
className={`${choice.isCorrect ? 'is-valid':''}`}
value={choice.isCorrect === null ? "0" : "1"}
/>
<label htmlFor={choice._key}>{choice.title}</label>
</ChoiceStyle>
))}
<ButtonComponent
type="button"
buttonType="second"
title="Sjekk svar"
onClick={() => {
calculateScore();
}}
/>诀窍是以下三元条件:
className={`${choice.isCorrect ? 'is-valid':''}`}出现的问题是类被立即应用。除非用户单击了按钮组件,否则我不希望显示正确答案
然后,您需要向choice对象添加一个新属性,以便检查和使用它。让我们假设如下内容:
const choice={
key: "some key"
isCorrect: true
/// other fields
}
// more code
{quiz.questions.map((question, index) => (
<ContentWrapper key={question._key}>
<h3>
{`${index + 1}. `}
{question.title}
</h3>
{question.choices.map(choice => (
<ChoiceStyle id={"wrapper" + choice._key} key={choice._key}>
<input
type="radio"
id={choice._key}
name={question._key}
onChange={updateScore}
className={`${choice.isValid ? 'is-valid':'' }`}
value={choice.isSelected === null ? "0" : "1"}
/>
<label htmlFor={choice._key}>{choice.title}</label>
</ChoiceStyle>
))}
<ButtonComponent
type="button"
buttonType="second"
title="Sjekk svar"
onClick={() => {
calculateScore();
}}
/>在每个updateScore中,您将需要检查选择是否正确以及是否与您的业务逻辑匹配,并添加新属性(isValid)来触发它。
const updateScore =()=>{
// some unknown logic
// some validations and then:
choice.isValid = true,
}由于(我已经假设)您将quiz设置为React的状态,因此新属性将强制刷新状态,并在用户单击时应用类名。
https://stackoverflow.com/questions/66026942
复制相似问题