【问题标题】:I am creating a checkbox list with react-native-elements. How do I check only one box at a time?我正在使用 react-native-elements 创建一个复选框列表。如何一次只检查一个框?
【发布时间】:2019-04-18 11:48:50
【问题描述】:

我正在制作一个复选框列表,但是当我按下一个复选框时,它会检查所有复选框。我想一次选择一个。

我尝试了 react-native-elements 1.1.0 文档中的示例代码以及其他人的示例,但我找不到解决方案。

constructor() {
    super();

    this.state = {
      checked1: false,
      checked2: false,
    };
  }

render() {
    return (
      <View style={styles.container}>
        <ScrollView>
          <CheckBox
            checkedIcon='dot-circle-o'
            uncheckedIcon='circle-o'
            title='checkbox 1'
            checkedColor='red'
            checked1={this.state.checked1}
            onPress={() => this.setState({ checked1: !this.state.checked1 })}
          />
          <CheckBox
            checkedIcon='dot-circle-o'
            uncheckedIcon='circle-o'
            title='checkbox 2'
            checkedColor='red'
            checked2={this.state.checked2}
            onPress={() => this.setState({ checked2: !this.state.checked2 })}
          />
        </ScrollView>
      </View>
    );
  }
}

我想一次选择一个复选框(选择我按下的复选框,而不是一次选择所有复选框)。

【问题讨论】:

  • 这两个复选框的状态不同,您需要单独的状态。您可以尝试添加状态checked1checked2,并根据它们各自的复选框进行相应的排列吗?
  • 您好,感谢您的回复。我实际上尝试过,但是当我这样做时,当我单击时,它不会检查任何内容:(我将更新代码以向您展示我所做的@kenmistry
  • 哦。我在下面分享了我的答案,它完全相同:P。你能看看测试链接吗?我已经完成了。您可以单独选中该框。

标签: javascript ios react-native checkbox react-native-elements


【解决方案1】:

好的,我已经为你创建了一个简单的测试here

基本上,如果您为每个复选框单独分配一个单独的状态,它会起作用。

  constructor() {
      super();

      this.state = {
        checked1: false,
        checked2: false,
      };
    }

  render() {
    return (
      <View style={styles.container}>
        <ScrollView>
          <CheckBox
            checkedIcon='dot-circle-o'
            uncheckedIcon='circle-o'
            title='checkbox 1'
            checkedColor='red'
            checked={this.state.checked1}
            onPress={() => this.setState({ checked1: !this.state.checked1 })}
          />
          <CheckBox
            checkedIcon='dot-circle-o'
            uncheckedIcon='circle-o'
            title='checkbox 2'
            checkedColor='red'
            checked={this.state.checked2}
            onPress={() => this.setState({ checked2: !this.state.checked2 })}
          />
        </ScrollView>
      </View>
    );
  }

【讨论】:

  • 实际上,我得到了它的工作!我放了checked1和check2而不是checked。感谢您的帮助:D @kenmistry
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多