我正在尝试从后端获取数据API的同时实现一个复选框,但是我遇到的问题是所有复选框均已选中,我无法取消选中它,以及如何将选中的选中复选框作为参数传递到下一个组件。
希望我能有所帮助。
这就是我当前代码中的内容;
class Gifts extends Component {
constructor(props){
super(props);
this.state={
users:'',
checked: {},
selected: 0
}
}
句柄复选框的API代码 handleChange = (index) => {
let { checked } = this.state;
checked[index] = !checked[index];
this.setState({ checked });
}
onPress(value) {
this.setState({ selected: value });
}
render() {
let { navigation } = this.props
return (
<SafeAreaView style={{flex:1 }}>
<View style={{ flex:1,justifyContent: 'center'}}>
//...codes..//
<View style={styles.userlist}>
<FlatList
data={this.state.users}
keyExtractor={(item ,index) => index.toString()}
renderItem={({ item }) => (
<FlatList
data={item.friendList}
renderItem={({ item }) =>
<View style= {{flexDirection:'row', justifyContent:'space-between'}}>
<Text style={{marginTop:20, marginLeft:10, fontSize: 20}}>{item.name}</Text>
<CheckBox
center
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={this.state.checked}
value={ this.state.checked[item.flag]}
onPress={this.onPress}
/>
</View>
}
keyExtractor={(item ,index) => index.toString()}
ItemSeparatorComponent ={this.ItemSeparator}
/>
)}
/>
</View>
<Button
rounded
// disabled={true}
//onPress={}
style={{width: 100, justifyContent: 'center',marginLeft:150}}
>
<Text>Send</Text>
</Button>
</View>
</SafeAreaView>
);
}
}
最佳答案
代码的问题在于,您为所有复选框使用了一个this.state.checked
,这很难操作。
一种更简单的方法是将标志checked
(及其值)集成到循环的FlatList数据中,在示例中,您将看到类似:this.state.users[i].friendList[j].checked = true/false
因此,对于每个元素,您都可以控制checked的值。
您必须将onPress函数更改为setState选中/未选中的元素
编辑解决方案可能是:
onPress函数(还必须为每个 friend 使用checked=false
初始化用户对象):
onPress(indexUser, indexFriend, value) {
const { users } = this.state;
for (let i = 0; i < users.length; i++) {
if (i === indexUser) {
for (let j = 0; j < users[i].friendList.length; j++) {
if (j === indexFriend) {
const bool = users[i].friendList[j].checked;
users[i].friendList[j].checked = !bool;
users[i].friendList[j].value = value;
}
}
}
}
this.setState({ users });
}
复选框组件(您已经嵌套了平面列表,也许可以进行一些重构):<CheckBox
center
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked={item.checked}
value={item.value}
onPress={()=>{ this.onPress(indexUser, indexFriend, value) }}
/>
关于android - 如何在FlatList React Native中实现复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62561446/