简体   繁体   中英

Get Flatlist ItemSeparatorComponent trailing item?

The Flatlist lets you define an ItemSeparatorComponent that receive as default props highlighted and leadingItem . The leading Item represents the item displayed before the Separator.

The problem is that I am using inverted on my Flatlist and my Seperators now need to adapt to the next item instead of the previous one.

Is there any way to access the item displayed after the Separator? Something like a trailingItem?

If you want to have the trailing item, you can use separators.updateProps to add a custom property. Below I have used the example from the FlatList docs and modified it slightly. In this example we are highlighting the trailing separator of the clicked item and we are adding the trailingItem to the props of ItemSeparatorComponent .

Output:

输出

Code:

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>

renderItem:

  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>
    );
  }

Explanation:

The whole magic happens here:

onShowUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: true})}

From the docs we can see, that updateProps expects the following two parameters:

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

newProps (Object)

First we select trailing , afterwards we can add our custom prop. We are adding the trailingItem prop and we are overriding the highlighted prop. Now we can access our props in the ItemSeparatorComponent with props.trailingItem (see above, i leaved a comment on the specific line).

Working Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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