【问题标题】:FlatList ScrollToIndex with onEndReached带有 onEndReached 的 FlatList ScrollToIndex
【发布时间】:2020-02-07 07:17:23
【问题描述】:

我有一个不同高度的 cmets 的 FlatList,我需要在使用此 FlatList 打开模式时实现滚动到某些特定元素。

由于某种原因,如果我将 ScrollToIndex 放入 ComponentDidMount 中,则会多次调用 onEndReached 方法。是否有任何解决方法可以滚动到列表的具体元素?

scrollToOffset、initialScroll 不是一个选项,因为我有不同的高度。

尝试使用此提示并 scrollToIndex inside promise

如果我再次单击该按钮,它可以正常工作,但第一次打开时位置略有不同,就像它没有时间滚动或其他什么。

  render() {
    const { comments } = this.props;
    return (
        <FlatList
          data={comments}
          refreshing={false}
          ref = {(ref) => {this.flatListRef = ref}}
          keyExtractor={this.keyExtractor}
          onRefresh={this.refresh}
          renderItem={this.renderItem}
          onEndReached={this.fetchMore}
          //initialScrollIndex={8} // works only for android
          onScrollToIndexFailed={()=>{}}
          onEndReachedThreshold={0.01}
          // removeClippedSubviews // dont uncomment!!! cause init white list on IOS
          ListEmptyComponent={this.renderEmpty}
        />
    );
  }
   componentDidMount (){
      let wait = new Promise((resolve) => {
          setTimeout(resolve, 400)
      });
      wait.then( () => {
          if(this.props.elementToScrollIndex && this.props.comments) {
            this.flatListRef.scrollToIndex({
              index: this.props.elementToScrollIndex,
              viewPosition: 0
            });
          }
      });
   }

【问题讨论】:

    标签: react-native react-redux react-native-flatlist


    【解决方案1】:

    Flatlist 可以被认为是一个项目的循环,一个一个地呈现。因此,另一个可能的工作选项是在渲染后滚动到每个项目。

    renderItem({ item, index }: {item: CommentType, index: number}) { 
      if(this.flatListRef &&
         this.props.elementToScrollIndex &&
         index <= this.props.elementToScrollIndex) {
           setTimeout(()=>{
             this.flatListRef.scrollToIndex({ index: index });
           }
      }
      return (<Comment item={item} index={index} />);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 1970-01-01
      • 2021-07-04
      • 2021-04-29
      • 2018-10-26
      • 2020-04-06
      • 2018-05-01
      • 2019-05-28
      • 1970-01-01
      相关资源
      最近更新 更多