React Native中如何修改FlatList选中列表项的展示颜色
React Native FlatList字母选中态区分实现方案
你已经在state中存储了当前选中的字母,只需要做2处核心调整即可实现需求:
- 给FlatList组件添加
extraData={selectedLetter}属性,FlatList默认只会在data属性变化时重新渲染,绑定extraData后会监听对应状态的变更触发刷新 - 在渲染单个字母项的逻辑中,判断当前遍历的字母是否为选中状态,给选中项应用差异化的样式
以下是修改后的完整可运行代码:
import React, { useState } from 'react' import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native' const WordPage = () => { const [selectedLetter, setSelectedLetter] = useState("A") const alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] const _renderAlphabet = ({ item }) => { // 判断当前项是否被选中 const isSelected = item === selectedLetter return ( <TouchableOpacity onPress={() => { setSelectedLetter(item) }}> {/* 选中态和默认态拼接不同样式 */} <View style={[styles.alphabetContainer, isSelected && styles.selectedAlphabetContainer]}> <Text style={[styles.alphabetText, isSelected && styles.selectedAlphabetText]}>{item}</Text> </View> </TouchableOpacity> ) } return ( <View style={styles.container}> <View> <FlatList data={alphabet} renderItem={_renderAlphabet} horizontal // 新增:绑定触发刷新的额外状态 extraData={selectedLetter} /> </View> <Text style={styles.text}>{selectedLetter}</Text> </View> ) } export default WordPage const styles = StyleSheet.create({ container: { flex: 1, }, alphabetContainer: { width: 24, height: 24, marginLeft: 14, marginTop: 14, justifyContent: 'center', alignItems: 'center', backgroundColor: 'green' }, // 新增:选中态容器样式,可按需调整颜色 selectedAlphabetContainer: { backgroundColor: 'orange' }, alphabetText: { fontSize: 18, color: 'white', }, // 新增:选中态文字样式,可按需调整 selectedAlphabetText: { color: '#000', fontWeight: 'bold' }, text: { fontSize: 100, justifyContent: 'center', alignSelf: 'center' } });
你可以根据设计需求自行修改selectedAlphabetContainer和selectedAlphabetText中的样式属性,调整选中态的视觉效果。
内容的提问来源于stack exchange,提问作者SoF
相关产品推荐
相关产品推荐

