在本机反应中第二次单击 onPress 后状态发生变化

时间:2021-01-15 10:52:57

标签: reactjs react-native

我为我的应用程序创建了一个自定义复选框。

constructor(props) {
    super(props);
    this.state = {
      checkValue1: false,
      color1: 'white',
    };
  }

checkBox1 = () => {
        if (this.state.checkValue1 == false) {
          this.setState({
            color1: 'white',
            checkValue1: true,
          });
        } else if (this.state.checkValue1 == true) {
          this.setState({
            color1: '#70AD47',
            checkValue1: false,
          });
        }
      };

  <TouchableOpacity style={styles.checkBorder} onPress={this.checkBox1}>
    <Icon name="checkmark" type="ionicon" size={20} color={this.state.color1} />
  </TouchableOpacity>


checkBorder: {
    backgroundColor: "blue",
    width: 20,
    height: 20,
    borderColor: '#7F7F7F',
    borderWidth: 1.5,
    borderRadius: 3,
  },

一切正常。但唯一的问题是,第二次单击后图标颜色会发生变化。之后,每次点击都会改变。问题只是它应该在第一次点击后改变颜色。我不知道我的代码遗漏了什么

1 个答案:

答案 0 :(得分:2)

试试这个方法

checkBox1 = () => {
  if (this.state.checkValue1 == false) {
    this.setState({
      color1: "#70AD47", // change here
      checkValue1: true,
    });
  } else if (this.state.checkValue1 == true) {
    this.setState({
      color1: "white",  // change here
      checkValue1: false,
    });
  }
};