Expo React Native FlatList点击事件实现及分类内容切换问题
解决方案
你需要通过状态管理选中的分类,实现默认选中、样式切换和内容切换,具体修改如下:
关键实现逻辑
- 用
useState维护当前选中的分类索引,默认设为Service对应的索引(假设myData数组第一个元素是Service) - 给分类标签添加点击事件,触发选中索引更新
- 动态设置文字样式,选中项添加下划线高亮
- 仅渲染当前选中分类的内容,而非所有分类内容
完整代码示例
import React, { useState } from 'react'; import { View, FlatList, TouchableOpacity, Text, StyleSheet } from 'react-native'; const DetailScreen = () => { // 示例数据,可根据实际业务调整结构 const myData = [ { name: 'Service', description: '这里是Service分类的详细内容' }, { name: 'Review', description: '这里是Review分类的详细内容' }, { name: 'About', description: '这里是About分类的详细内容' }, { name: 'Specialist', description: '这里是Specialist分类的详细内容' }, ]; // 默认选中第一个分类(Service) const [selectedIndex, setSelectedIndex] = useState(0); return ( <View style={styles.container}> {/* 横向分类标签栏 */} <FlatList data={myData} horizontal={true} showsHorizontalScrollIndicator={false} renderItem={({ item, index }) => ( <TouchableOpacity style={styles.tabItem} onPress={() => setSelectedIndex(index)} > <Text style={[ styles.nameText, selectedIndex === index && styles.selectedText, ]} > {item.name} </Text> </TouchableOpacity> )} keyExtractor={(item) => item.name} /> {/* 当前选中分类的内容展示区 */} <View style={styles.contentContainer}> <Text style={styles.contentText}> {myData[selectedIndex].description} </Text> </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, tabItem: { marginRight: 24, paddingVertical: 8, }, nameText: { fontSize: 16, color: '#333', }, selectedText: { borderBottomWidth: 2, borderBottomColor: '#007AFF', // 下划线颜色可自定义 color: '#007AFF', }, contentContainer: { marginTop: 24, flex: 1, }, contentText: { fontSize: 14, color: '#666', lineHeight: 22, }, }); export default DetailScreen;
核心修改说明
- 新增
selectedIndex状态变量,同时控制选中样式和内容渲染 - 点击分类标签时更新选中索引,触发视图重新渲染
- 通过样式数组合并,给选中的标签添加下划线和文字高亮
- 将内容展示区从FlatList的item中分离,单独渲染当前选中项的描述
内容的提问来源于stack exchange,提问作者Umar Milanzi Snr
相关产品推荐
相关产品推荐

