react-native - 获取 Flatlist ItemSeparatorComponent 尾随项目?
问题描述
Flatlist 允许您定义一个ItemSeparatorComponent作为默认 propshighlighted
和leadingItem
. 前导项表示在分隔符之前显示的项。
问题是我inverted
在我的 Flatlist 上使用,我的分隔符现在需要适应下一个项目而不是前一个项目。
有没有办法访问分隔符后显示的项目?像 trailingItem 之类的东西?
解决方案
如果您想拥有尾随项,可以使用separators.updateProps
添加自定义属性。下面我使用了FlatList 文档中的示例并稍作修改。在此示例中,我们突出显示了单击项目的尾随分隔符,并且我们将添加trailingItem
到 .props 中ItemSeparatorComponent
。
#输出:
#代码:
JSX:
<View style={styles.container}>
<FlatList
ItemSeparatorComponent={(props) => {
console.log('props', props); // here you can access the trailingItem with props.trailingItem
return (<View style={{height: 5, backgroundColor: props.highlighted ? 'green' : 'gray'}} />);
}}
data={data}
inverted
renderItem={({item, index, separators}) => renderItem(item,index,separators)}
/>
</View>
渲染项:
const renderItem = (item, index, separators) => {
return (
<TouchableHighlight
key={item.key}
onPress={() => console.log('onPress')}
onShowUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: true})}
onHideUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: false})}>
<View style={{backgroundColor: 'white', height: 50, justifyContent: 'center', alignItems: 'center'}}>
<Text>{item.id}</Text>
</View>
</TouchableHighlight>
);
}
#解释:
整个魔法发生在这里:
onShowUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: true})}
从文档中我们可以看到, updateProps 需要以下两个参数:
选择(枚举('领先','尾随'))
新道具(对象)
首先我们选择trailing
,然后我们可以添加我们的自定义道具。我们正在添加trailingItem
道具并且我们正在覆盖highlighted
道具。现在我们可以使用 props.trailingItem 访问 ItemSeparatorComponent 中的道具(见上文,我在特定行留下了评论)。
#工作示例:
推荐阅读
- ios - iOS:选择模拟器设备进行截图
- java - 从条件概率生成 DNA 序列
- ruby-on-rails - 基于三个连接属性的唯一性的 Rails 测试操作
- javascript - 如何将用户名记录到控制台?
- html - 想要删除容器之间的空间
- python - Python 和 Snowflake 使用 SQL Alchemy 引擎将新数据附加到现有表中正在返回当前会话没有当前数据库
- mysql - MySQL 自连接表 Next/Prev 行性能
- c# - 是什么导致 EF(核心)查询在此地理空间查询中的实际数据库查询过程中发生变化?
- php - PHP - 通过 curl 检索网页时出现“有效负载太大”错误
- java - 使用新关键字创建时在 Spring 存储库中自动装配