React Native实现FlatList单个TouchableOpacity点击切换背景色
解决React Native FlatList单个项点击切换背景色的问题
问题原因
你当前使用了全局的backgroundColor状态,所有列表项都绑定这个状态,导致点击任意项都会触发全局状态更新,所有项的背景色一起变化。要实现单个项独立切换,需要跟踪被选中的项ID,而非全局颜色值。
修改方案
- 将状态从单个颜色值改为存储选中的ID,初始值设为
null(表示无选中项) - 修改点击事件,接收当前项的ID,切换选中状态(点击已选中的项则取消选中)
- 每个列表项的背景色根据自身ID是否等于选中ID动态设置
修改后的完整代码
import { StyleSheet, Text, View, Image, FlatList, TouchableOpacity } from 'react-native' import React, { useState } from 'react' import Friends from '../database/Friends' const FriendsList = () => { // 存储选中的好友ID,初始无选中 const [selectedId, setSelectedId] = useState(null); const handlePress = (itemId) => { // 切换选中状态:当前选中该ID则取消,否则选中它 setSelectedId(prevId => prevId === itemId ? null : itemId); }; return ( <View style={{ marginHorizontal: 24, marginTop: 7, }}> <FlatList showsVerticalScrollIndicator={false} data={Friends} // 必加keyExtractor优化列表性能 keyExtractor={item => item.id.toString()} renderItem={({ item }) => <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}> <View style={{ flexDirection: 'row', alignItems: 'center' }}> <Image style={{ width: 40, height: 40, borderRadius: 20, marginRight: 12 }} source={item.profileImage} /> <View> <Text style={{ fontSize: 14, fontWeight: '500' }}>{item.name}</Text> <Text style={{ fontSize: 12, color: '#666' }}>{item.followers} Followers</Text> </View> </View> <TouchableOpacity style={{ backgroundColor: selectedId === item.id ? '#5669FF' : '#E2E2E2', height: 20, width: 20, borderRadius: 10, alignItems: 'center', justifyContent: 'center' }} onPress={() => handlePress(item.id)} > <Image style={{ width: 12, height: 12 }} source={require("../Assets/Icons/TickIcon.png")} /> </TouchableOpacity> </View> } /> </View> ) }; export default FriendsList
关键改动说明
- 状态优化:用
selectedId替代全局颜色状态,精准跟踪当前选中项 - 点击逻辑:
handlePress通过函数式更新判断,实现点击选中/取消选中的切换 - 动态样式:每个
TouchableOpacity的背景色通过selectedId === item.id的条件判断,仅选中项变色 - 性能补充:添加
keyExtractor,符合React Native列表组件的性能优化规范
内容的提问来源于stack exchange,提问作者MST intern 2
相关产品推荐
相关产品推荐

