如果在 react-native 中选中了特定复选框,我如何取消选中所有其他复选框
这是我的代码:
constructor(props, context) {
super(props, context);
console.log('custom/ccheckbox/index.js constructor()');
this.state = {
checked: false,
};
}
handleCheck() {
this.setState({checked: !this.state.checked});
}
render() {
return (
<CheckBox
iconType='material'
checkedIcon='check'
uncheckedIcon='check-box-outline-blank'
checkedColor={Colors.ORANGE}
checked={this.state.checked}
containerStyle={style.content}
onPress={() => this.handleCheck()}
/>
);
}
}
如果在句柄检查中使用其他内容,我该如何使用?
我不知道
你有多少输入,但你可以做这样的事情。
constructor(props, context) {
super(props, context);
console.log('custom/ccheckbox/index.js constructor()');
this.state = {
checked: "none",
};
}
handleCheck(checked) {
this.setState({ checked});
}
render() {
return (
<React.Fragment>
<CheckBox
iconType='material'
checkedIcon='check'
uncheckedIcon='check-box-outline-blank'
checkedColor={Colors.ORANGE}
checked={this.state.checked === "first"}
containerStyle={style.content}
onPress={() => this.handleCheck("first")}
/>
<CheckBox
iconType='material'
checkedIcon='check'
uncheckedIcon='check-box-outline-blank'
checkedColor={Colors.ORANGE}
checked={this.state.checked === "second"}
containerStyle={style.content}
onPress={() => this.handleCheck("second")}
/>
<CheckBox
iconType='material'
checkedIcon='check'
uncheckedIcon='check-box-outline-blank'
checkedColor={Colors.ORANGE}
checked={this.state.checked === "third"}
containerStyle={style.content}
onPress={() => this.handleCheck("third")}
/>
<CheckBox
iconType='material'
checkedIcon='check'
uncheckedIcon='check-box-outline-blank'
checkedColor={Colors.ORANGE}
checked={this.state.checked === "fourth"}
containerStyle={style.content}
onPress={() => this.handleCheck("fourth")}
/>
</React.Fragment>
);
}}
您可以将所有检查状态存储在一个对象中:
state = { checked: {} }
<CheckBox
checked={this.state.checked.chk1 }
onPress={() => this.setState(({ checked }) => ({
checked: {...checked, chk1: !checked.chk1 } // toggle this checkbox
}))}
/>
<CheckBox
checked={this.state.checked.chk2 }
onPress={() => this.setState(({ checked }) => ({
checked: { chk2: !checked.chk2 } // clears other checkboxes
}))}
/>