繁体   English   中英

获取 Flatlist ItemSeparatorComponent 尾随项目?

[英]Get Flatlist ItemSeparatorComponent trailing item?

Flatlist 允许您定义一个ItemSeparatorComponent ,该组件接收作为默认道具highlightedleadingItem 前导项表示显示分隔符之前的项。

问题是我在我的 Flatlist 上使用了inverted ,我的分隔符现在需要适应下一个项目而不是前一个项目。

有没有办法访问分隔符显示的项目? 像一个 trailingItem 之类的东西?

如果您想拥有尾随项,您可以使用separators.updateProps添加自定义属性。 下面我使用了FlatList 文档中的示例并稍微修改了它。 在这个例子中,我们突出显示了被点击项的尾随分隔符,我们将trailingItem添加到ItemSeparatorComponent的 props 中。

输出:

输出

代码:

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 中的道具(见上文,我在特定行上留下了评论)。

工作示例:

https://snack.expo.io/@tim1717/flatlist-separators

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM