【发布时间】:2019-10-21 19:09:31
【问题描述】:
大家好,我正在尝试使用复选框在 React Native 中制作测验应用程序,我有一个问题组件,但是当用户单击复选框时,我似乎无法更改复选框的值。
这是我的示例代码,您可能会指出,我做错了什么:
测验组件
import React, { Component } from 'react';
import { View Image, CheckBox} from 'react-native';
import { Text } from 'react-native-elements';
import questions from '../assets/questions.json';
class Quiz extends Component {
constructor() {
super();
this.state = {};
this.question = questions[0].question;
this.answers = Object.entries(questions[0].answers).map(([key, value], index) => {
this.state[key] = false;
return <View key={index}>
<Text>{ value } { this.state[key].toString() }</Text>
<CheckBox value= { this.state[key] } onChange={() => this.checkboxClicked(key) } />
</View>
});
}
checkboxClicked = (key) => {
this.setState({ a: true })
}
render() {
return (<View>
<Text h4>{ this.question} </Text>
{ this.answers }
</View> );
};
};
export default Quiz;
问题 JSON:
[
{
"question": "Who is the strongest?",
"answers": {
"a": "Superman",
"b": "The Terminator",
"c": "Waluigi, obviously"
},
"correctAnswer": "c"
},
{
"question": "What is the best site ever created?",
"answers": {
"a": "SitePoint",
"b": "Simple Steps Code",
"c": "Trick question; they're both the best"
},
"correctAnswer": "c"
},
{
"question": "Where is Waldo really?",
"answers": {
"a": "Antarctica",
"b": "Exploring the Pacific Ocean",
"c": "Sitting in a tree",
"d": "Minding his own business, so stop asking"
},
"correctAnswer": "d"
}
]
我试图在用户单击复选框时将复选框的状态更改为已选中并从 true 更改为 false,但是当我使用 setState 时就像没有发生任何事情一样??
【问题讨论】:
标签: javascript reactjs react-native