首页 > 解决方案 > 如何在本机反应中使用复选框?

问题描述

我得到了用户可以选择的主题列表,之后我将根据他们选择的主题进行 api 调用,我得到了一切工作,但我需要将文本更改为复选框

这是我的状态:

     this.state = {
      loading: false,
      dataSource: [],
      error: null,
      topic: '',
  }

这是我的api调用:

   getUsers = () => {
    fetch('https://someapi.com/?topic=' + this.state.topic, {method: 'GET'}).then((response) => response.json()).then((responseJson) => {
      this.setState({
        loading: false,
        error: responseJson.error || null,
        dataSource: responseJson.data.users,
      });
    }).catch((error) => {
      this.setState({error, loading: false});
    });
  }

这里我的渲染方法主题运行良好,但我需要将文本更改为复选框:

    <View>
     <Text onPress={(text) => this.setTopic('topic-slug1')}>Some Topic</Text>
     <Text onPress={(text) => this.setTopic('topic-slug2')}>Some Topic</Text> 
     <Text onPress={(text) => this.setTopic('topic-slug3')}>Some Topic</Text>           
    </View>

这是setTopic()功能:

   setTopic(searchedTopic) {
    this.setState({topic: searchedTopic});
  }

我只需要使用Checkboxes insted<Text>即可在AndroidIOS上使用

标签: react-nativejsx

解决方案


确保,您必须根据选中的复选框添加条件是真还是假

这是一个带有插件的演示:https ://github.com/crazycodeboy/react-native-check-box#readme

constructor(props){
    super(props);
    this.state = {
        topic: null,
        checkTopic1: false,
        checkTopic2: false,
        checkTopic3: false,
    }
}

setTopic = (slug) => {
    if(slug == "topic-slug1"){
        this.setState({
            checkTopic1:!this.state.checkTopic1
        })
    }else if(slug == "topic-slug2"){
        this.setState({
            checkTopic2:!this.state.checkTopic2
        })
    }else if(slug == "topic-slug3"){
        this.setState({
            checkTopic3:!this.state.checkTopic3
        })
    }
    this.setState({
        topic: slug
    })
    this.getUsers();
}

getUsers = () => {
    fetch('https://someapi.com/?topic=' + this.state.topic, {method: 'GET'}).then((response) => response.json()).then((responseJson) => {
      this.setState({
        loading: false,
        error: responseJson.error || null,
        dataSource: responseJson.data.users,
      });
    }).catch((error) => {
      this.setState({error, loading: false});
    });
}


<View>
    <CheckBox
        style={{flex: 1, padding: 10}}
        onClick={()=> this.setTopic('topic-slug1')}
        isChecked={this.state.checkTopic1}
        leftText={"Some Topic"}
    />
    <CheckBox
        style={{flex: 1, padding: 10}}
        onClick={()=> this.setTopic('topic-slug2')}
        isChecked={this.state.checkTopic2}
        leftText={"Some Topic"}
    />
    <CheckBox
        style={{flex: 1, padding: 10}}
        onClick={()=> this.setTopic('topic-slug3')}
        isChecked={this.state.checkTopic3}
        leftText={"Some Topic"}
    />
</View>

推荐阅读