更改onPress背景的特定按钮(响应本机)

时间:2018-12-28 18:00:36

标签: react-native

我正在尝试进行一个简单的测验。我想将按钮的背景更改为绿色(如果正确),将其更改为红色(如果按钮不正确)。我的问题是如何只选择一个按钮?目前,我只能让所有按钮变色。

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>)
        });
    }
}

1 个答案:

答案 0 :(得分:1)

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)}>
  })

,并且数组中的item对象应如下所示:。

{
 id: '0',
 status: true/false  
}

我认为这会有所帮助。