我正在做测验应用程序,我需要做最后一步,但我不知道如何做。我有所有数据都包含的数组,并且每个数组都有正确的选项。在函数中,我比较按钮的索引是否等于正确的选项,如果按钮未被单击,则加1分。但是,当我尝试单击第二个问题时,我不能,因为首先我将click:false设置为。 如果我从问题中单击按钮,我需要做的是不能再单击一次,但是在其他问题中,我可以单击它。请帮帮我。 我将在测验10中提出问题,所以我不想为每个问题都设置状态,也不想在按钮中使用禁用功能。 代码:
class Quiz extends React.Component {
constructor(props) {
super(props);
this.state =
{
questions: [{title: "Question-1", answers:['a', 'b', 'c', 'd'],
correct:2}, {title: "Question-2", answers:['a', 'b', 'c', 'd'],
correct:0}],
numbers: [0, 1, 2],
progress:0,
score:0,
click: true
}
this.checkAnswer = this.checkAnswer.bind(this);
}
checkAnswer(correct, index) {
var newScore = 0;
if (correct === index && this.state.click) {
newScore = this.state.score+1;
this.setState({score: newScore, click: false});
}
}
render() {
return (
<div>
{
this.state.questions.map(({title, answers, correct}, i) => (
<div key={i} className="card">
<div className="card-body">
<h1>{title}</h1>
{answers.map((answers, j) =>
<button key={j} onClick={ () => {
this.checkAnswer(correct, j);
}}>{answers}</button>
)}
</div>
</div>
))
}
<p>{this.state.score}</p>
</div>
);
}
}
const Root = document.getElementById("root");
ReactDOM.render(<Quiz />, Root);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
答案 0 :(得分:1)
您非常确定。关于相同问题的哪个问题?第五?
只要正确回答,只需在每个问题中添加信息。
您在这里:
class Quiz extends React.Component {
constructor(props) {
super(props);
this.state =
{
questions: [{title: "Question-1", answers:['a', 'b', 'c', 'd'],
correct:2}, {title: "Question-2", answers:['a', 'b', 'c', 'd'],
correct:0}],
numbers: [0, 1, 2],
progress:0,
score:0
}
this.checkAnswer = this.checkAnswer.bind(this);
}
checkAnswer(q, i) {
if (q.correct === i && !q.answered) {
q.answered = true;
this.setState({score: this.state.score + 1});
}
}
render() {
return (
<div>
{
this.state.questions.map((q, i) => (
<div key={i} className="card">
<div className="card-body">
<h1>{q.title}</h1>
{q.answers.map((answer, j) =>
<button key={j} onClick={ () => {
this.checkAnswer(q, j);
}}>{answer}</button>
)}
</div>
</div>
))
}
<p>{this.state.score}</p>
</div>
);
}
}
const Root = document.getElementById("root");
ReactDOM.render(<Quiz />, Root);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
答案 1 :(得分:0)
那么显然cllick选项应该是问题的一部分,而不是整个状态通用的,那么您可以这样做
this.state.questions.map(({title, answers, click, correct}, i) => (
<div key={i} className="card">
<div className="card-body">
<h1>{title}</h1>
{answers.map((answers, j) =>
<button key={j} onClick={ () => {
click && this.checkAnswer(correct, j);
}}>{answers}</button>
)}