FlatList 上的 ReactNative scrollToEnd() - 功能组件

ReactNative scrollToEnd() on FlatList - Functional Component

我正在尝试使用 ReactNative 实现聊天应用程序。我面临的问题是,在将新项目添加到 FlatList 后,我试图将 FlatList 项目滚动到底部,以便新添加的消息可见。

当我查看文档时,我可以看到一个名为 scrollToEnd() 的方法。但不确定如何按照功能组件编码风格使用它。因为当我用谷歌搜索时,我可以看到它在 Class 组件样式编码中使用 ref 的示例。

但是找不到如何在功能组件中使用它!

我想你正在寻找 useRef

// I hope you don't mind the typescript
import {useRef} from 'react';
import {FlatList} from 'react-native';

export const Comp = () => {
    const flatListRef = useRef<FlatList<any>>();

    // however you detect new items
    flatListRef?.current?.scrollToEnd();

    return (
        <FlatList
            data={[]}
            renderItem={() => null}
            ref={flatListRef}
        />
    );
}

但我认为如果你在平面列表上使用 inverted={true},它应该会吸附到顶部,或者更好的底部(我认为)。

对于打字稿,您可以只使用:

const listRef = useRef<FlatList>(null);

在您的代码中,您只需要检查您的引用是否存在:

listRef?.current?.scrollToIndex({animated: true, index: yourIndex})