React Native中如何在屏幕加载时滚动到顶部?

3

我在HomeScreen中使用Flatlist,它显示了多个帖子。现在我想要的是,每当我从应用程序中退出或关闭应用程序,然后再打开应用程序时,我都应该能够看到Flatlist中的第一项。

我尝试在我的渲染函数中使用scrollToIndex,但它给了我一个错误 -undefined is not an object (evaluating '_this2.refs.flatListRef.scrollToIndex')

<FlatList 
    data={this.state.data}
    ref={(ref) => { this.flatListRef = ref; }}
    renderItem={ ({item,index}) =>  this._renderItem(item,index) }
    extraData={[ this.state.data, this.state.checked ]}
/>

我曾尝试在componentDidMountrender函数中使用以下代码this.refs.flatListRef.scrollToIndex({animated: true,index:0});,但是没有成功。


这个问题可以通过使用ref作为回调函数,然后调用this.flatListRef.scrollToIndex({animated: true,index:0})来解决。 - Pritish Vaidya
@PritishVaidya 我尝试在Flatlist的render函数中使用它,但仍然无法正常工作。 - Shubham Bisht
2个回答

1

ComponentDidMount回调函数在用户离开应用并稍后恢复它后不会运行。您必须使用AppState:

AppState可以告诉您应用程序是在前台还是后台,并在状态更改时通知您。 [来源]

根据您的需求调整给定示例,并使用this.flatListRef.scrollToIndex({animated: true,index:0})滚动。


我尝试使用官方React Native文档中使用的AppState,但是AppStateaddEventListener处理程序(函数)似乎不起作用。您能告诉我正确使用AppState的方法吗? - Shubham Bisht

0

import { ScrollView, } from 'react-native';

import {useScrollToTop} from '@react-navigation/native';

const ref = React.useRef(null);

useScrollToTop(ref);

const goToTopClickAction = () => { ref.current?.scrollTo({ y: 0, animated: true, }); };

在 ScrollView 标签中添加 ref={ref}

< ScrollView ref={ref}> < /ScrollView >


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接