reactjs - 添加类 onclick
问题描述
我正在制作反应测验应用程序。而且我想创建将类添加到活动元素的函数,但在我的代码中,它将活动类添加到数组中的所有元素。我不知道如何仅将类添加到单击的按钮。请帮帮我。
//...
this.state =
{
questions: [
{
title: "Question-1", answers:['a', 'b', 'c', 'd'],
correct: 2,
answered: false,
},
{
title: "Question-2", answers:['a', 'b', 'c', 'd'],
correct: 0,
answered: false,
}
],
score:0,
}
this.checkAnswer = this.checkAnswer.bind(this);
}
checkAnswer(i, j) {
const { questions, score } = this.state;
if (questions[i].correct === j && !questions[i].answered) {
questions[i].answered = true;
this.setState(
{
score: score + 1,
questions,
});
}
}
render() {
return (
<div>
{
this.state.questions.map((q, i) => (
//...
{
q.answers.map((answer, j) =>
(
<button
className={q.answered ? 'active' : ''}
key={j}
onClick={() => {
this.checkAnswer(i, j);
}}
>
{answer}
//...
解决方案
使用此代码,如果回答了一个问题,它会将活动的 className 添加到您的所有答案按钮中。我认为您需要在 answers 数组中保留一个选定的属性。
questions: [
{
title: "Question-1",
answers: [
{
text: "a",
selected: true
},
{
text: "b",
selected: false
},
{
text: "c",
selected: false
},
{
text: "d",
selected: false
}
],
correct: 2,
answered: false,
}
]
要使所选答案的 className 处于活动状态,您的代码必须是:
q.answers.map((answer, j) =>
(
<button
className={a.selected ? 'active' : ''}
key={j}
onClick={() => {
this.checkAnswer(i, j);
}}
>
{answer}
...
推荐阅读
- mongodb - MongoDB:如何根据日期间隔和一个匹配间隔中所有日期的另一个条件进行查询
- docker - 无法使用 helm 在 Kubernetes 上使用持久存储设置 docker 私有注册表
- go - 导入本地模块
- sql - 为什么 sql 代码有效而 sql 之类的 scala 代码无效?(使用左连接和几个日期)
- airflow - 气流:为什么我注销后仍然显示dags?
- .net - 如果导入项目是 .NET Core SDK 项目,如何签入 props 文件
- php - 路径查找算法来查找从一个地方到另一个地方的路线
- ios - 为什么 ViewController 不能完全适应 iPad 的屏幕?
- php - 如何在 laravel 5.6 中检查特定 id 是否有密码?
- typescript - 在 Observable 中使用正则表达式过滤