我在
FlatList
中创建了一个 React Native
。const Friends = [
{
id: 1,
name: 'Alex Lee',
profileImage: require("../Assets/FriendsImages/f1.png"),
followers: '246',
},
{
id: 2,
name: 'Micheal Ulasi',
profileImage: require("../Assets/FriendsImages/f2.png"),
followers: '106',
},
.......
.......
]
export default Friends
FlatList 代码
import { StyleSheet, Text, View, TextInput, Image, FlatList, TouchableOpacity } from 'react-native'
import React, { useState } from 'react'
import Friends from '../database/Friends'
const FriendsList = () => {
const [backgroundColor, setBackgroundColor] = useState('#E2E2E2');
const handlePress = () => {
setBackgroundColor(backgroundColor === '#E2E2E2' ? '#5669FF' : '#E2E2E2');
};
return (
<View style={{ marginHorizontal: 24, marginTop: 7, }}>
<FlatList
showsVerticalScrollIndicator={false}
data={Friends}
renderItem={({ item }) =>
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 16 }}>
<Image style={{...}}
source={item.profileImage}/>
<View>
<Text style={{...}}>{item.name}</Text>
<Text style={{...}}>{item.followers} Folloers</Text>
</View>
</View>
<TouchableOpacity
style={{ backgroundColor: backgroundColor, height: 20, width: 20, borderRadius: 10, }}
onPress={handlePress}>
<View style={{ alignItems: 'center', justifyContent: 'center',height: 20, width: 20, }}>
<Image style={{...}} source={require("../Assets/Icons/TickIcon.png")} />
</View>
</TouchableOpacity>
</View>}
/>
</View>)}
export default FriendsList
现在,我想在按下时更改
backgroundColor
的 TouchableOpacity
。就我而言,当我按其中一个时,它会更改所有背景颜色。但我只想要 TouchableOpacity 改变按下的颜色。
创建一个单独的
useState
挂钩来存储用户在 FlatList
样式中单击的 TouchableOpacity
项目 id 使用三元运算符检查用户单击的 id 是否与 FlatList
项目 id 相同,将背景颜色设置为“#5669FF”,否则给'#E2E2E2'
更新 FlatList 代码:像这样的代码
import React, { useState } from 'react'
import Friends from '../database/Friends'
const FriendsList = () => {
const [selectedId,setSelectedId] = useState('');
<FlatList
showsVerticalScrollIndicator={false}
data={Friends}
renderItem={({ item }) =>
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 16 }}>
<Image style={{...}}
source={item.profileImage}/>
<View>
<Text style={{...}}>{item.name}</Text>
<Text style={{...}}>{item.followers} Folloers</Text>
</View>
</View>
<TouchableOpacity
style={{ backgroundColor: item.id == selectedId ? '#5669FF' : '#E2E2E2', height: 20, width: 20, borderRadius: 10, }}
onPress={() =>setSelectedId(item.id}>
<View style={{ alignItems: 'center', justifyContent: 'center',height: 20, width: 20, }}>
<Image style={{...}} source={require("../Assets/Icons/TickIcon.png")} />
</View>
</TouchableOpacity>
</View>}
/>
</View>)}
export default FriendsList