gpt4 book ai didi

javascript - 如何只选中选中的复选框并在 React Native 中获取它的值?

转载 作者:行者123 更新时间:2023-11-30 11:18:57 29 4
gpt4 key购买 nike

我使用 React Native 创建了一组复选框,允许用户选择他们可能喜欢的选项。但是我遇到的问题是同时选中了所有复选框并且无法获得它的值(value)。对于复选框,我使用这个包 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>
);
}
}

我希望当用户选中一个复选框时,只选中该复选框并获取它的值。

我该怎么做?

最佳答案

为了确保只选择一个选项,使用单选按钮会更自然。但是您也可以使用复选框来实现:

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>
);
}
}

关于javascript - 如何只选中选中的复选框并在 React Native 中获取它的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50542816/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com