首页 > 解决方案 > FlatList scrollToIndex 方法不会滚动到正确的索引

问题描述

实际行为:

我正在开发一个在 react-native 中播放应用程序并在其中实现轨道播放器的播客。当我在播放器屏幕中播放播客时,点击下一个图标两次,然后导航到当前播放器屏幕中正在播放的播客的主题屏幕,然后我需要从 FlatList 滚动到正在播放的播客项目主题屏幕并将其显示为突出显示。

为此,我将FlatList 的scrollToIndex方法与 FlatList 的getItemLayout属性结合使用,并将当前正在播放的播客项目的索引传递给该方法。但是该方法没有按预期工作,并且滚动到错误的位置。我也尝试了许多没有用的解决方法。

预期行为:

我应该从播放器屏幕的主题屏幕滚动到正在播放的特定播客项目,并将其显示为突出显示。有人能帮助我吗。提前致谢。

我尝试过的:

 <FlatList
    showsVerticalScrollIndicator={false}
    style={{ marginLeft: 20, marginRight: 20 }}
    ref={(ref) => {
      this.flatListRef = ref;
    }}
    initialScrollIndex={insights.length > 50 ? 50 : 40}
    initialNumToRender={2}
    getItemLayout={this.getItemLayout}
    data={insights}
    extraData={this.state}
    stickyHeaderIndices={[0]}
    keyExtractor={this._keyExtractor}
    renderItem={this._renderItem}
    ListHeaderComponent={playAll ? null : this._renderHeader}
    ItemSeparatorComponent={ListSeparator}
    contentContainerStyle={{...Styles.listBottomSpace}}
    legacyImplementation={false}
    windowSize={20}
    maxToRenderPerBatch = {1}
    removeClippedSubviews={false}
    onScrollToIndexFailed={(error) => {
             this.flatListRef.scrollToOffset({ offset: error.averageItemLength * 
             error.index, animated: false });
                  setTimeout(() => {
                    if (insights.length !== 0 && this.flatListRef !== null) {
                      this.flatListRef.scrollToIndex({ index: error.index, animated: false 
       });
                    }
                  }, 100);
                }}
      />

getItemHeight = (event) => {
    if (!this.itemHeight) {
      const { height } = event.nativeEvent.layout;
      this.itemHeight = height;
    }
  };
  getItemLayout = (data, index) => {
    let height = this.itemHeight ? this.itemHeight : 100;
    return { length: height, offset: height * index, index };
  };
  scrollToItem = (insights) => {
    const { currentTrack } = this.props;
    let activeInsight = currentTrack ? lodash.findIndex(insights, (insight) => {
      return (insight.insight_id === Number(currentTrack.id) && insight.insight_title === 
      currentTrack.title)
    }) : -1;
    this.flatListRef &&
      activeInsight > -1 && 
      this.flatListRef.scrollToIndex({
        animated: false,
        index: activeInsight,
        viewPosition: 0.5,
      })
  };

环境 :

“反应”:“16.8.3”,“反应原生”:“0.59.9”,“MacOS”:“10.15.3”

标签: react-nativereact-native-flatlistscrolltoindex

解决方案


我只在 iOS 上遇到了同样的问题。有时 scrollToIndex 函数不会滚动到特定索引。不知何故,我的解决方案是将索引作为字符串而不是 int 发送。在 Adrian-Gapriel Peslar 解决方案中,您会看到他也在使用 "" + 索引。


推荐阅读