获取 Flatlist ItemSeparatorComponent 尾随项?

Get Flatlist ItemSeparatorComponent trailing item?

Flatlist 允许您定义一个 ItemSeparatorComponent 作为默认道具 highlightedleadingItem。前导项目表示显示在分隔符之前的项目。

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

有什么方法可以访问在分隔符之后显示的项目吗?类似 trailingItem 的东西?

如果你想有尾随项,你可以使用separators.updateProps添加自定义属性。下面我使用了 FlatList docs 中的示例并稍作修改。在此示例中,我们突出显示了单击项的尾随分隔符,并将 trailingItem 添加到 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 需要以下两个参数:

select (enum('leading', 'trailing'))

newProps (Object)

首先我们selecttrailing,然后我们可以添加我们的自定义道具。我们正在添加 trailingItem 道具,我们正在覆盖 highlighted 道具。现在我们可以使用 props.trailingItem 访问 ItemSeparatorComponent 中的道具(见上文,我在特定行上留下了评论)。

#工作示例:

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