我正在尝试构建一个简单的测验。如果按钮正确,我想将按钮的背景更改为绿色,如果不正确,则更改为红色。我的问题是如何只选择一个按钮?目前我只能让所有按钮变色。
export default class TestScreen extends React.Component {
constructor(props){
super(props);
this.qno = 0
this.score = 0
const jdata = jsonData.quiz.quiz1
arrnew = Object.keys(jdata).map( function(k) { return jdata[k] });
this.state = {
question : arrnew[this.qno].question,
options : arrnew[this.qno].options,
correctoption : arrnew[this.qno].correctoption,
countCheck : 0,
back_colour: 'gray',
answered: false,
}
}
change_colour(ans) {
if(this.state.answered == false){
if(ans == this.state.correctoption){
Alert.alert('Correct!');
this.setState({ back_colour: 'green'})
}
else {
Alert.alert('Wrong!');
this.setState({ back_colour: 'red'})
}
this.setState({ answered: true })
}
else {
// Do nothing
}
}
render() {
let _this = this
const currentOptions = this.state.options
const options = Object.keys(currentOptions).map( function(k) {
return ( <View key={k} style={{margin:10}}>
<Button color={_this.state.back_colour} onPress={() => _this.change_colour(k)} title={currentOptions[k]} />
</View>)
});
}
}
yeah its great and easy with react . You can use ids for this purpose.
例。。
validateUser = id => {
const newItems = items.map(item => {
if(item.id === id ) {
then check anwer here
and trun status true or false ..
}
})
}
items.map(item function() {
<Button color={item.status ? 'red' : 'black' } onPress={() =>
this.validateAnswer(item.id)}>
})
数组中的项目对象应该是这样的..
{
id: '0',
status: true/false
}
我认为这会有所帮助.