因此,我正在一个项目中使用“响应本机元素”复选框,最后我在不选择所有提取项的情况下使它工作。它一次只能选择一个,如果我尝试选择另一个项目,它将取消选择第一个项目,然后选择第二个项目。但是现在,它不允许我一次选择多个项目。我已经在这个平台上搜索了google,并且也进行了reddit的搜索,我找不到任何解决方案。
这是我的代码
constructor(props) {
super(props);
this.state = {
dataSource: [],
checked: null,
}
}
render() {
const { navigation } = this.props;
const cust = navigation.getParam('food', 'No-User');
const other_param = navigation.getParam('otherParam', 'No-User');
const cust1 = JSON.parse(cust);
const data = cust1;
console.log(data);
return (
<View style={styles.container}>
<BackButtonMGMT navigation={this.props.navigation} />
<FlatList
data={data}
extraData={this.state}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) => (
<CheckBox
center
titleProps={{ color: 'black', fontWeight: 'bold'}}
title={item}
iconRight
checked={this.state.checked == item}
size={30}
onPress={() => this.setState({checked: item})}
containerStyle={styles.checkBox}
/>
)}
/>
</View>
)
}
我尝试更改CheckBox中的选中行。我已经尝试过check = {!! item.checked},但是它不起作用。我已经尝试过check = {!this.state.checked},但这也不起作用。有没有人遇到过这个问题,如果可以的话,您是如何解决的?
答案 0 :(得分:0)
现在,您的状态有一个参数checked
,用于存储项目的选中状态。这意味着每次您选择另一个复选框时,先前的选择都会丢失。要允许多个选择,我们必须管理一组复选框状态。这可以通过不同的方法来实现,这是我建议的方法
首先,您需要修改构造函数
constructor(props) {
super(props);
const { navigation } = props;
const cust = navigation.getParam('food', 'No-User');
const other_param = navigation.getParam('otherParam', 'No-User');
const cust1 = JSON.parse(cust);
//Here we will make array of object with additional parameter, checked
//This assume cust1 will be ["Pecan Cookies", "Strawberry Cheesecake"]
const data = cust1.map(item=>({label:item, checked:false});
this.state = {
dataSource: [],
data,
checked: null,
}
}
现在让我们更新渲染功能
onChecked = (index) => {
let {data} = this.state;
data[index].checked = !data[index].checked;
this.setState({data})
}
render() {
const { data} = this.state;
return (
<View style={styles.container}>
<BackButtonMGMT navigation={this.props.navigation} />
<FlatList data={data} extraData={this.state} keyExtractor={(item, index)=> index.toString()}
renderItem={({ item, index }) => (
<CheckBox center titleProps={{ color: 'black', fontWeight: 'bold'}} title={item.label} iconRight
checked={item.checked} size={30} onPress={()=>this.onChecked(index)}
containerStyle={styles.checkBox}
/>
)}
/>
</View>
)
}
这应该可以解决问题或选择多项。