【问题标题】:Checkbox not Rendering or Changing Checked value when state is changing状态更改时复选框未呈现或更改选中值
【发布时间】:2018-08-14 07:36:25
【问题描述】:
我必须将 Checkbox 的值从 Unchecked 更改为 Checked,反之亦然。
为此,我正在更改按钮单击的状态。
如果“checked”状态值为“true”,则应选中 Checkedbox。但是,它不是。
我使用了“已检查”属性并分配了状态的布尔值。
因此,它应该在状态将要更改但未更改时呈现。
还有其他方法可以渲染 Checkbox 吗?
【问题讨论】:
标签:
react-native
checkbox
state
react-native-android
react-native-ios
【解决方案1】:
这是一个代码示例如何做到这一点
class App extends Component {
state = {
isChecked: false
};
render() {
return (
<View>
<CheckBox
value={this.state.isChecked}
onValueChange={() =>
this.setState({
isChecked: !this.state.isChecked
})
}
/>
</View>
);
}
}
【解决方案2】:
如果您使用的是 redux-form,那么这就是您的解决方案:
<Field name="AcceptTAndC" component={(props) => {
return (
<View>
<ListItem>
<CheckBox {...props.input} checked={props.input.value ? true : false} onPress={() => {
const val = !props.input.value;
props.input.onChange(val);
this.setState({ acceptTAndC: val });
}} />
<Text> I accept <Text onPress={() => this.refs.termsModal.open()}>this terms and conditions</Text></Text>
</ListItem>
</View>
)
}} validate={[acceptTerms]}/> // "acceptTerms" is validation rules that imported from other file, but you may not need it for this
您可以从这里查看详细信息code 和output
【解决方案3】:
正如@Amila Dhulanjana 上面提到的,这个函数只改变分配状态值的值,但在你分配选中的字段之前它不会更新 HTML 视图中的复选框。
class App extends Component {
state = {
isChecked: false,
};
render() {
return (
<View>
<CheckBox
value={this.state.isChecked}
checked={this.state.isChecked}
onValueChange={() =>
this.setState({
isChecked: !this.state.isChecked,
})
}
/>
</View>
);
}
}