react-native-elements复选框更新值

时间:2018-08-14 07:06:08

标签: react-native checkbox state

我有以下代码,由于某些原因,当我单击它们时,复选框未更新。有谁知道可能是什么问题?我正在使用来自react-native-elements的CheckBox。选中的属性基于集合中是否存在值。 onpress函数会更新状态变量,并且我能够从状态变量中获取正确的值。谢谢!

  constructor(props) {
    super(props);

    this.state = {
      interests: new Set(),
      brands: new Set(),
      medicalCondition: new Set(),
      errorMessage: '',
      loading: false
    }
  }

  onPressHandler = (event, value, keyName) => {
    let tempCheckedValues = new Set(this.state[keyName]);
    tempCheckedValues.has(value) ? tempCheckedValues.delete(value) : tempCheckedValues.add(value);
    console.log(tempCheckedValues);
    this.setState({[keyName] : tempCheckedValues});
  }

  renderCheckboxGroup = (checkboxList, keyName) => {
    return checkboxList.map((value, index) => {
      return (
          <CheckBox 
            key={index}
            title={value}
            onPress={(event) => this.onPressHandler(event, value, keyName)}
            checked={this.state[keyName].has(value.toLowerCase())}
          />
      )
    })
  }

  render() {
    const interestsConst = ["Tennis", "Golf", "Shopping", "Movie", "Hiking", "Reading", "Diving", "Investing"];
    const brandsConst = ["Chanel", "Louis Vuitton", "H&M", "ZARA", "Hermes", "Gucci", "Cartier", "Burberry", "Nike", "Adidas", "Lululemon", "Athleta"];
    const medicalConditionConst = ["Hypertension", "Hyperlipidemia", "Diabetes", "Back pain", "Anxiety", "Asthma", "Cancer", "Depression", "Shingles"];

    return (
      <View style={styles.container}>
        <ScrollView>
          <View style={styles.cardGroup}>
            <Card title='Interests'>
              {this.renderCheckboxGroup(interestsConst, 'interests')}
            </Card>
          </View>
          <View style={styles.cardGroup}>
            <Card title='Brands'>
              {this.renderCheckboxGroup(brandsConst, 'brands')}
            </Card>
          </View>
          <View style={styles.cardGroup}>
            <Card title='Medical Conditions'>
              {this.renderCheckboxGroup(medicalConditionConst, 'medicalCondition')}
            </Card>
          </View>
        </ScrollView>
      </View>
    )
  }
}

0 个答案:

没有答案