我使用React Native创建一组复选框,允许用户选择他们喜欢的选项。但我遇到的问题是,同时检查所有复选框并且无法获得它的值。对于复选框,我使用此包react-native-circle-checkbox这是我的代码:
class Answer extends Component {
constructor(prop) {
super(prop);
this.state = {
checked: false,
checkboxValue: [
{
label: "Option1",
value: 1
},
{
label: "Option2",
value: 2
},
{
label: "Option3",
value: 3
},
{
label: "Option4",
value: 4
},
{
label: "Option5",
value: 5
}
]
};
}
CheckMe = (value, index) => {
this.setState({
checked: !this.state.checked
});
console.log(index);
};
render() {
const options = this.state.checkboxValue;
return (
<View style={styles.mainContainer}>
<View style={styles.questionWrapper}>
<View style={styles.questionGroup}>
<View style={{ flexDirection: "row" }}>
{options.map(option => {
return (
<CircleCheckBox
key={option.value}
checked={this.state.checked}
onToggle={(value, index) => this.CheckMe()}
labelPosition={LABEL_POSITION.RIGHT}
label={option.label}
styleLabel={{ fontSize: 17 }}
/>
);
})}
</View>
</View>
</View>
</View>
);
}
}
我希望当用户选中复选框时,只选中复选框并获取其值。
我该怎么做?
答案 0 :(得分:1)
为确保只选择一个选项,使用单选按钮会更自然。但你也可以通过复选框实现这一目标:
class Answer extends Component {
constructor(prop) {
super(prop);
this.state = {
selectedCheckbox: {}, // keep selected item in state, by default its empty meaning nothing is selected
checkboxValue: [
{
label: "Option1",
value: 1
},
{
label: "Option2",
value: 2
},
{
label: "Option3",
value: 3
},
{
label: "Option4",
value: 4
},
{
label: "Option5",
value: 5
}
]
};
}
CheckMe = selectedCheckbox => {
this.setState({ selectedCheckbox }); // update selected item
};
render() {
const { checkboxValue, selectedCheckbox } = this.state;
return (
<View style={styles.mainContainer}>
<View style={styles.questionWrapper}>
<View style={styles.questionGroup}>
<View style={{ flexDirection: "row" }}>
{checkboxValue.map((option, indexInArray) => {
return (
<CircleCheckBox
key={option.value}
checked={option.value === selectedCheckbox.value} // for current element
onToggle={(value, index) => this.CheckMe(option)} // pass index of toggled element
labelPosition={LABEL_POSITION.RIGHT}
label={option.label}
styleLabel={{ fontSize: 17 }}
/>
);
})}
</View>
</View>
</View>
</View>
);
}
}