如何识别FlatList的最后一项 实现列表项间加逗号且无尾部多余逗号
FlatList列表项逗号分隔需求实现方案
你可以通过以下两种方式解决多余逗号的问题:
方案1:直接在渲染逻辑中判断非最后项追加逗号
仅需要对现有代码的逗号输出逻辑增加一层下标判断,只有当前项不是数组最后一个元素时才输出逗号,修改后的代码如下:
<FlatList data={job.schedule} renderItem={({ item, index }) => ( <View style={[[Layout.center], {}]}> <Text style={[[Fonts.textInterRegular12]]}> {item.dayHuman.slice(0, 3)} {index < job.schedule.length - 1 ? ', ' : ''} </Text> </View> )} horizontal keyExtractor={item => item.id} extraData={this.state} showsVerticalScrollIndicator={false} />
该方案修改成本极低,适合不需要后续调整分隔符样式的简单场景。
方案2:使用FlatList原生ItemSeparatorComponent属性实现
FlatList官方提供了专门用于渲染列表项之间分隔内容的属性ItemSeparatorComponent,该属性渲染的内容只会出现在相邻两个列表项之间,天然不会在首尾出现,代码更符合框架设计规范,后续维护也更方便,实现代码如下:
<FlatList data={job.schedule} renderItem={({ item }) => ( <View style={[[Layout.center], {}]}> <Text style={[[Fonts.textInterRegular12]]}> {item.dayHuman.slice(0, 3)} </Text> </View> )} ItemSeparatorComponent={() => <Text style={Fonts.textInterRegular12}>, </Text>} horizontal keyExtractor={item => item.id} extraData={this.state} showsVerticalScrollIndicator={false} />
如果后续需要修改分隔符的样式、增加边距等需求,直接修改ItemSeparatorComponent返回的组件即可,不需要改动列表项的渲染逻辑。
内容的提问来源于stack exchange,提问作者ilvthsgm
相关产品推荐
相关产品推荐

