[英]How can I find the first and last item in a React Native sectionList?
我有一个带有部分的 sectionList。 我想在整个列表中找到第一个和最后一个项目。 因此,如果列表有 10 个项目和 3 个部分,我想在索引 0 处找到项目并在索引 9 处找到项目。
这样做的目的是我想为整个 sectionList 中的第一个和最后一个项目设置样式,并且我编写的任何逻辑最终都会为每个部分之间的第一个或最后一个项目设置样式。
提醒一下,sectionList renderItem 方法提供:
<SectionList
sections={data}
renderItem={({item, index, section}) => {
// How to access the first and last items in this entire List. Not just the first
// and the last item in between each section.
<List.Item
title={item.title}
style={{
backgroundColor: 'gray',
}}
/>
}
/>
这是一个 Expo 小吃,可能有助于开始使用它。 如何使此部分列表中的第一个和最后一个项目具有不同的背景颜色?
https://snack.expo.dev/@onrun/sectionlist-example
谢谢!
您可以按如下方式提取并存储最后一项:
const lastItem = React.useMemo(() => {
const last = DATA[DATA.length - 1].data;
return last[last.length - 1];
}, []);
然后,为第一个和最后一个项目着色:
renderItem={({ item, index }) => {
return (
<Item
title={item}
style={{
backgroundColor:
(index === 0 && DATA[index].data[0] === item) ||
(index === DATA.length - DATA[DATA.length - 1].data.length - 1 &&
lastItem === item)
? 'red'
: 'yellow',
}}
/>
);
}}
我已更新Item
以接收样式道具。
const Item = ({ title, style }) => (
<View style={[styles.item, style]}>
<Text style={styles.title}>{title}</Text>
</View>
);
结果如下所示,这是一个小吃:
仅使用SectionList
属性没有解决方案。 但是,您可以通过创建一个简单的 function 来检查元素是跨节的第一个还是最后一个。
const isFirstOrLast = (index, section, globalData) => {
return (index === 0 && section.title === globalData.at(0).title) ||
(index === section.data.length - 1 && section.title === globalData.at(-1).title)
}
做它喜欢
<SectionList
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item, index, section }) => {
return <Item style={isFirstOrLast(index, section, DATA) ? { backgroundColor: "white" } : {}} title={item} />;
}}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
如本工作示例所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.