【问题标题】:How to scroll to top when screen loads in React Native?在 React Native 中加载屏幕时如何滚动到顶部?
【发布时间】:2019-07-01 15:56:52
【问题描述】:

我在 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 ]}
/>

这就是我在componentDidMount 和内部渲染函数this.refs.flatListRef.scrollToIndex({animated: true,index:0}); 中尝试使用的,但没有奏效。

【问题讨论】:

  • this.flatListRef.scrollToIndex({animated: true,index:0}) 应该修复它,因为您使用 ref 作为回调。
  • @PritishVaidya 我尝试在 Flatlist 的渲染函数中使用它,但它仍然无法正常工作

标签: android reactjs react-native react-native-flatlist


【解决方案1】:

ComponentDidMount 回调不会在用户离开应用并稍后恢复后运行。您必须改用AppState

AppState 可以告诉你应用是在前台还是后台,并在状态改变时通知你。 [Source]

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

【讨论】:

  • 我尝试使用官方 React Native 文档中使用的 AppState,但 AppStateaddEventListener 处理程序(函数)似乎不起作用。你能告诉我什么是使用 AppState 的正确方法吗?
【解决方案2】:

进口{ 滚动视图, } 来自 'react-native';

从“@react-navigation/native”导入 {useScrollToTop};

const ref = React.useRef(null);

useScrollToTop(ref);

const goToTopClickAction = () => { ref.current?.scrollTo({ y: 0, 动画:真实, }); };

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

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    相关资源
    最近更新 更多