react-native - 如何在本机反应中使用复选框?
问题描述
我得到了用户可以选择的主题列表,之后我将根据他们选择的主题进行 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>
即可在Android和IOS上使用
解决方案
确保,您必须根据选中的复选框添加条件是真还是假
这是一个带有插件的演示: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>
推荐阅读
- javascript - Gulp 抛出错误“必须使用导入来加载 ES 模块”
- python - 检测 Python 解释器并从 WiX 安装程序安装站点包
- slack - 如何为 Slack 创建一个将更新聚合到一个单一频道的插件?
- sql - 在 Spark SQL 中为时间戳添加可变小时数
- node.js - Robo 3T 中的错误...无法连接到 localhost:27017
- c - 睡眠指令不适用于信号处理程序
- r - 我正在尝试在 R 中运行 XGBoost,但遇到了一些问题
- node.js - 当我输入“npm run serve”时,我得到一个 SyntaxError。错误是:意外的令牌,预期的“,”(45:2)。我究竟做错了什么?
- node.js - 带有 Vue 的节点,请求和 API 的不同端口
- mongodb - 如何在 mongodump 后自动运行 mongorestore