Efficient way to scroll to certain index in FlatList with variable item size

后端 未结 1 907
无人共我
无人共我 2021-01-04 18:21

I\'m having a trouble adding scroll/jump to certain index functionality on FlatList in react-native. My FlatList items are vary in size (height) which makes me unable to imp

相关标签:
1条回答
  • 2021-01-04 18:37

    You can dynamically split your data according to scroll direction. If scroll goes up prepend data to your state and same for opposite direction. Then use onScrollToIndexFailed like this :

    <FlatList
      ref={this.flatListRef}
      data={this.state.data}
      renderItem={() => <View> <SomeComponent /> </View>}
      initialNumToRender={this.state.data.length / 5}
      onEndReached={(e) => {
        // Append data
      }}
      onScroll={(e) => {
        if (e.nativeEvent.contentOffset.y == 0) {
          // Prepend data
        }
      }}
      onScrollToIndexFailed={(error) => {
        this.flatListRef.scrollToOffset({ offset: error.averageItemLength * error.index, animated: true });
        setTimeout(() => {
          if (this.state.data.length !== 0 && this.flatListRef !== null) {
            this.flatListRef.scrollToIndex({ index: error.index, animated: true });
          }
        }, 100);
      }}
    />   
    

    You can workaround this issue. This worked for me and took me a lot of time to get that work :))

    0 讨论(0)
提交回复
热议问题