我正在尝试实施具有多项选择功能的平面列表,但是当我按一个项目时,它将更改所有项目的背景,我该如何解决?
state = {
authUsers: [],
selMembers: [],
selected: false
}
render() {
const renderUser = (item) => (
<TouchableOpacity style={[styles.item, { backgroundColor: this.state.selected ? '#DDD' : '#FFF' }]} onPress={() => this.selectItem(item.key)}>
<Avatar rounded size="medium" source={{ uri: item.avatar }} />
<View>
<Text style={styles.memberName}>{item.name}</Text>
</View>
</TouchableOpacity>
)
return (
<View style={{ marginTop: StatusBar.currentHeight }}>
<FlatList
style={{ padding: 6 }}
data={this.state.authUsers}
keyExtractor={(item) => item.id}
renderItem={({ item }) => renderUser(item)}
/>
</View>
)
}
答案 0 :(得分:1)
state = {
authUsers: [{
key: 1,
item_name: 'AAA',
},
{
key: 2,
item_name: 'BBB',
},
{
key: 3,
item_name: 'CCC',
},
{
key: 4,
item_name: 'DDD',
},]
}
selectItem(key) {
let authUsers = [...this.state.authUsers]
for (let item of authUsers) {
if (item.key == key) {
item.isSelected = (item.isSelected == null) ? true : !item.isSelected;
break;
}
}
this.setState({ authUsers });
}
render() {
const renderUser = (item) => (
<TouchableOpacity style={[styles.item, { backgroundColor: item.isSelected ? '#DDD' : '#FFF' }]} onPress={() => this.selectItem(item.key)}>
<Avatar rounded size="medium" source={{ uri: item.avatar }} />
<View>
<Text style={styles.memberName}>{item.name}</Text>
</View>
</TouchableOpacity>
)
return (
<View style={{ marginTop: StatusBar.currentHeight }}>
<FlatList
style={{ padding: 6 }}
data={this.state.authUsers}
keyExtractor={(item) => item.id}
renderItem={({ item }) => renderUser(item)}
/>
</View>
)
}