大家好,我想在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时,什么也没发生?
答案 0 :(得分:1)
看起来您好像没有使用传递给onClick处理程序的密钥。试试:
checkboxClicked = (key) => {
this.setState({ [key]: true })
}
,如果要切换它:
checkboxClicked = (key) => {
this.setState({ [key]: !this.state[key] })
}