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

React Native中如何在FlatList的偶数下标项显示指定文本

实现方案

FlatList 的 renderItem 回调自带当前项的索引参数index,通过判断index的值即可实现条件渲染:

  • 注意JS数组从0开始计数,你需要的第2、4、6、8项(从1开始数的偶数位)对应索引值为1、3、5、7...,判断条件为 index % 2 === 1
  • 如果你实际需要的是数组索引为偶数的项(对应第1、3、5...项),把判断条件改为index % 2 === 0即可

修改后的完整代码如下:

// 从renderItem参数中解构出index
const renderItem = ({ item, index }) => (
    <TouchableOpacity>
        <Text>{item.name}</Text>
        {/* 满足条件时才渲染指定Text组件 */}
        {index % 2 === 1 && <Text>我想要仅在第2、4、6、8…个数组项中显示这段文本</Text>}
    </TouchableOpacity>
);

<FlatList
    data={product}
    renderItem={renderItem}
    keyExtractor={item => item.id}
    ListEmptyComponent={<EmptyData />}
    style={{ flex: 1, marginBottom: 50 }}
/>

提示:你原示例代码中的Text结束标签漏写了斜杠,需要统一改成</Text>才能正常运行。

内容的提问来源于stack exchange,提问作者Mr-T

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:06:04