React Native中FlatList实现3列网格显示更多/收起、初始展示3项的方法
实现步骤
- 第一步:在组件内声明状态控制展示范围
// 引入useState(如果是类组件用state管理即可) import { useState } from 'react'; // 组件内部声明状态 const [showAll, setShowAll] = useState(false);
- 第二步:修改FlatList的数据源,根据状态动态返回展示的数组项
- 第三步:给FlatList添加尾部自定义组件,渲染显示更多按钮,数组总长度≤3时不展示按钮
修改后完整代码
// 需提前从react-native导入TouchableOpacity组件 <FlatList data={showAll ? item.tag : item.tag.slice(0, 3)} renderItem={({ item }) => ( <View style={{ flex: 1, flexDirection: "column", margin: 1 }}> <View style={{ backgroundColor: "#aaf0d1", borderRadius: 20, borderWidth: 1, padding: "2%", borderColor: "#40e0d0", width: widthToDp("25%"), flex: 1, flexDirection: "column", margin: 1 }} > <Text numberOfLines={1} style={{ fontSize: 15, fontWeight: "300" }}> #{item.title} </Text> </View> </View> )} numColumns={3} keyExtractor={(item, index) => index} // 添加尾部按钮 ListFooterComponent={() => { // 数组总数量小于等于3时不显示按钮 if (item.tag.length <= 3) return null; return ( <TouchableOpacity style={{ padding: 10, alignItems: 'center', marginTop: 8 }} onPress={() => setShowAll(!showAll)} > <Text style={{ color: '#40e0d0' }}> {showAll ? '收起' : '显示更多'} </Text> </TouchableOpacity> ); }} />
说明
你原本配置的numColumns={3}已经实现了每行最多展示3个项的效果,不需要额外调整布局逻辑。如果不需要收起功能,把按钮点击逻辑直接改成setShowAll(true),展开后隐藏按钮即可。
内容的提问来源于stack exchange,提问作者vjtechno
相关产品推荐
相关产品推荐

