[英]ReactJs: How can I show the correct questionnaire answer and the total score?
我是新來的人,我想在同一頁面上安排每個問題的正確選項。 同樣,當問題解決后,它應顯示它是否正確。 最后,我需要總分。 我該怎么做? 謝謝您的幫助。
這是我到目前為止所做的。.(通常會有更多問題,但我必須刪除它們才能發布)
const questionsArray = [
{
question: 'When the C programming language has first appeared?',
option1: '1970',
option2: '1971',
option3: '1972'
},
{
question: 'When the Java programming language has first appeared?',
option1: '1994',
option2: '1995',
option3: '1996'
},
];
class QuizAppQuestion extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
currentQuestionIndex: 0,
questions: [],
answers: []
};
}
componentDidMount() {
this.setState({questions: questionsArray})
}
onChangeOption(value) {
const {currentQuestionIndex} = this.state;
let answers = {...this.state.answers};
answers[currentQuestionIndex] = value;
this.setState({answers});
}
handleNext() {
let incrementCurrentQuestionIndex = this.state.currentQuestionIndex + 1;
this.setState({currentQuestionIndex: incrementCurrentQuestionIndex});
}
render() {
const {questions, currentQuestionIndex, answers} = this.state;
if (!questions.length) {
return <div>Loading questions...</div>
}
if (currentQuestionIndex >= questions.length) {
return (<div><h3>End of the quiz</h3></div>)
}
const {question, option1, option2, option3} = questions[currentQuestionIndex];
return (<div>
<h1>Question {currentQuestionIndex + 1}</h1>
<h4>{question}</h4>
<label>
<input type='radio' checked={answers[currentQuestionIndex] === option1} value={option1} onChange={(evt) => this.onChangeOption(evt.target.value)}/>
{option1}
</label>
<br/>
<label>
<input type='radio' checked={answers[currentQuestionIndex] === option2} value={option2} onChange={(evt) => this.onChangeOption(evt.target.value)}/>
{option2}
</label>
<br/>
<label>
<input type='radio' checked={answers[currentQuestionIndex] === option3} value={option3} onChange={(evt) => this.onChangeOption(evt.target.value)}/>
{option3}
</label>
<hr/>
<button onClick={() => this.handleNext()}>Next</button>
</div>);
}
}
您可能希望創建一個單獨的數組來保存答案,然后針對答案數組中的相應問題/答案測試所選答案。 因此,在您的情況下,例如:
const answerArray = [
{
question: "When the C programming language has first appeared?",
answer: "option1"
}
]
onSubmit = (selectedAnswer) => { // Selected answer is the option picked from your select menu
if(selectedAnswer === answerArray[currentQuestionIndex].answer) {
// Logic for correct answer
} else {
// Logic for incorrect answer
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.