因此,基本上,我正在创建一个测验组件,我需要遍历所有问题,但一次只显示一个问题,在回答问题后,再显示另一个。
我该怎么做?我通常会使用for循环,但不建议这样做,如何使用.map()或任何其他函数实现相同的结果?
这基本上就是我想要发生的事情
for(let i = 0; i < quiz.questions.length(); i++) {
return (
<Content>
<View style={styles.gutter}>
<View style={styles.container}>
<View style={styles.content}>
<Text>{quiz.questions[i].question}</Text>
</View>
<Button
primary
label={quiz.answers.option1}
onPress={() => {
quiz.answers.option1 === quiz.questions[i].rightAnswer
? continue // would continue work here as expected?
: console.log("Wrong");
}}></Button>
<Button
primary
label={quiz.answers.option2}
onPress={() => {
quiz.answers.option2 === quiz.questions[i].rightAnswer
? continue // would continue work here as expected?
: console.log("Wrong");
}}></Button>
<Button
primary
label={quiz.answers.option3}
onPress={() => {
quiz.answers.option3 === quiz.questions[i].rightAnswer
? continue // would continue work here as expected?
: console.log("Wrong");
}}></Button>
</View>
</View>
</Content>
);
}
答案 0 :(得分:4)
您应该使用useState挂钩创建一个功能组件:
import React, { useState } from 'react';
function Quiz() {
const [index, setIndex] = useState(1);
const current = quiz.questions[index];
return (
<Content>
<View style={styles.gutter}>
<View style={styles.container}>
<View style={styles.content}>
<Text>{current.question}</Text>
</View>
<Button
primary
label={quiz.answers.option1}
onPress={() => {
if (quiz.answers.option1 === current.rightAnswer) {
setIndex(index + 1);
} else {
console.log('Wrong');
}
}}
/>
<Button
primary
label={quiz.answers.option2}
onPress={() => {
if (quiz.answers.option2 === current.rightAnswer) {
setIndex(index + 1);
} else {
console.log('Wrong');
}
}}
/>
<Button
primary
label={quiz.answers.option3}
onPress={() => {
if (quiz.answers.option3 === current.rightAnswer) {
setIndex(index + 1);
} else {
console.log('Wrong');
}
}}
/>
</View>
</View>
</Content>
);
}
答案 1 :(得分:0)
如果只想显示一个答案,则应编写如下代码:
我认为您已经想加载一件商品,并且收到undefined
错误消息,所以这就是为什么您要问的问题
假设您正在通过redux的属性获取数据(可以是常规状态)
Render(){
<div>
{this.props.mydata &&
this.props.mydata.quiz[0] &&
this.props.mydata.quiz[0].question
}
</div>
}
此代码检查您的数据,只要加载了数据就可以使用它,并且不会出现任何错误。而且只要您的播放器正确回答,它就必须在阵列中+1。
我希望你有主意并为你工作