You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在主FlatList中嵌套展示子FlatList以实现商品分类层级展示

React Native 商品分类主列表嵌套适配子列表实现方案

你现有的数据请求逻辑无需修改,仅需要调整主FlatList的renderItem逻辑,在有子适配产品的分类下嵌套子FlatList即可,完整实现代码如下:

import { FlatList, View, Text, Image } from 'react-native';

// 主列表组件
<FlatList
  data={products}
  keyExtractor={item => item.id.toString()}
  renderItem={({ item }) => (
    <View style={{ marginVertical: 12 }}>
      {/* 一级分类标题 */}
      <Text style={{ fontSize: 17, fontWeight: '600', paddingHorizontal: 16, marginBottom: 8 }}>
        {item.category_name}
      </Text>

      {/* 存在子适配产品时渲染子FlatList */}
      {Array.isArray(item.sub_products) && item.sub_products.length > 0 ? (
        <FlatList
          data={item.sub_products}
          keyExtractor={subItem => `sub_${subItem.id}`}
          scrollEnabled={false} // 禁用子列表独立滚动,和父列表滚动行为联动
          // 如需子列表横向滚动可打开下面两个配置,删除numColumns即可
          // horizontal={true}
          // scrollEnabled={true}
          numColumns={2} // 控制子产品每行展示数量,可按需调整
          contentContainerStyle={{ paddingHorizontal: 8 }}
          renderItem={({ item: subItem }) => (
            <View style={{ width: '50%', padding: 8 }}>
              <Image 
                source={{ uri: subItem.cover_image }} 
                style={{ width: '100%', height: 120, borderRadius: 8 }}
                resizeMode="cover"
              />
              <Text style={{ marginTop: 6, fontSize: 14 }} numberOfLines={1}>{subItem.product_name}</Text>
              <Text style={{ color: '#ff4d4f', marginTop: 4, fontSize: 15 }}>¥{subItem.sell_price}</Text>
            </View>
          )}
        />
      ) : (
        {/* 无适配子产品的分类直接渲染主商品项 */}
        <View style={{ marginHorizontal: 16, padding: 12, backgroundColor: '#f5f5f5', borderRadius: 8 }}>
          <Image 
            source={{ uri: item.cover_image }} 
            style={{ width: '100%', height: 160, borderRadius: 8 }}
            resizeMode="cover"
          />
          <Text style={{ marginTop: 8, fontSize: 15 }}>{item.product_name}</Text>
          <Text style={{ color: '#ff4d4f', marginTop: 4, fontSize: 16, fontWeight: '500' }}>¥{item.sell_price}</Text>
        </View>
      )}
    </View>
  )}
/>

注意事项

  • 代码中用到的category_name、sub_products、cover_image、product_name、sell_price均为示例字段,你需要替换为接口返回的实际对应字段
  • 安卓端如果出现嵌套滚动不流畅的问题,可以给父子FlatList都添加nestedScrollEnabled={true}属性
  • 所有样式均可根据你的设计需求自行调整

内容的提问来源于stack exchange,提问作者John Ocean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 02:39:03