【问题标题】:How to detect checkbox checked or not using react native?如何使用本机反应检测复选框是否选中?
【发布时间】:2020-08-13 13:10:56
【问题描述】:
在我的场景中,我正在尝试为checkbox 检查或uncheck 编写逻辑。如果检查意味着需要打印一些字符串或取消选中意味着需要打印其他东西。如何使用 react native 实现这一点?
下面是我的代码
checked={this.state.checked}
onPress={() => {
this.actiondone();
}}
actiondone(){
//Here how to detect checked or not with if else
}
【问题讨论】:
标签:
android
ios
typescript
react-native
【解决方案1】:
您可以使用您的状态来实现此目的。如果当您按下复选框时您的状态当前处于选中状态 (this.state.checked = true),则预期状态未选中,反之亦然。然后,您可以将您的状态设置为与原来相反。
所以基本上你对复选框的当前状态做相反的事情,然后将状态设置为所需的状态(异步)。
类似于以下内容:
<CheckBox
checked={this.state.checked}
onPress={() => this.actionDone()}
/>
actionDone() {
if (this.state.checked) {
// Do what you want when the checkbox is unchecked
} else {
// Do what you want when the checkbox is checked
}
// Set the checkbox to the desired state
this.setState({checked: !this.state.checked})
}