我使用带有checkbox的ListItems。列表中的每一项都包含checkBox。我无法选中或unCheck复选框,也无法选中listItems中的所有复选框。我用'checkBoxTest()‘和'selectAll()’做了两个函数,我想我没有正确使用setState。以下是我的代码
import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import { ListItem, checkBox } from 'react-native-elements';
const list = [
{
name: 'PinkMan',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
subtitle: 'Vice President'
},
{
name: 'Mr White',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
subtitle: 'Vice Chairman'
},
]
export default class Members extends Component {
constructor(props) {
super(props);
this.state = {
checked: false,
}
}
selectAll(){
this.setState({checked: !this.state.checked})
}
checkBoxTest() {
this.setState({checked: !this.state.checked})
}
keyExtractor = (item, index) => index.toString()
renderItem = ({ item }) => (
<ListItem
title={item.name}
subtitle={item.subtitle}
leftAvatar={{
source: item.avatar_url && { uri: item.avatar_url },
title: item.name[0]
}}
checkBox={{
checkedColor: '#744DD2',
uncheckedColor: 'grey',
onPress: this.checkBoxTest,
checked: this.state.checked,
}}
bottomDivider
/>
)
render() {
return(
<>
<View style={{ bottom: 60 }}>
<FlatList
keyExtractor={this.keyExtractor}
data={list}
renderItem={this.renderItem}
/>
</View>
<View>
<TouchableOpacity onPress={this.selectAll} >
<Text style={styles.textStyle}>Select All</Text>
</TouchableOpacity>
</View>
</>
);
}
}发布于 2020-02-15 13:16:48
尝试将extraData={this.state}传递给您的FlatList组件。
https://facebook.github.io/react-native/docs/flatlist#extradata
编辑:
您可能只想传递extraData={this.state.checked}。仅当选中状态更改时,才应重新呈现FlatList。根据需要传递其他道具。
发布于 2020-02-17 12:00:47
您似乎忘记了绑定this.selectAll()和checkBoxTest()
如果你想把一个函数传递给onPress(),首先你需要在构造函数中绑定它。
this.selectAll = this.selectAll.bind(this);
this.checkBoxTest = this.checkBoxTest.bind(this);将这两条语句放在构造函数中。
https://stackoverflow.com/questions/60234641
复制相似问题