React Native Expo VirtualizedList 如何使用 scrollToEnd 方法?

React Native Expo VirtualizedList how to use scrollToEnd method?

我正在尝试在 VirtualizedList 上使用 scrollToEnd() 方法。但有趣的是,我在互联网上找不到任何示例来解释如何使用 VirtualizedList 的方法。

我试着像下面这样使用它,但显然它没有用

<VirtualizedList
          data={serverData}
          initialNumToRender={4}
          renderItem={renderItem}
          keyExtractor={item => item.id.toString()}
          getItemCount={getItemCount}
          getItem={getItem}
          ListFooterComponent={renderFooter}
          scrollToEnd={{ animated: true }}
        />  

VirtualizedListscrollToEnd 公开为方法而不是道具。您必须使用 React Ref 才能访问它。

const listRef = React.useRef(null)

// Scroll to list end - Call this function after add new items to list for example
const scrollToListEnd = ()=> listRef.current?.scrollToEnd({ animated: true })

<VirtualizedList
  data={serverData}
  initialNumToRender={4}
  renderItem={renderItem}
  keyExtractor={(item) => item.id.toString()}
  getItemCount={getItemCount}
  getItem={getItem}
  ListFooterComponent={renderFooter}
  ref={listRef}
/>;


scrollToEnd函数由VirtualizedList继承自ScrollView。它是一个函数,而不是一个道具。

您需要创建对列表组件的引用并使用该引用调用函数。这可以按如下方式完成。


const listRef = useRef(null);

<VirtualizedList
    ref= {listRef}
    onContentSizeChange= {()=> listRef.current.scrollToEnd()} 
/> 

当数据的内容大小发生变化时,上面的代码会滚动到列表的末尾。但是,您可以随时调用 scrollToEnd 函数。