react-navigation v4下每次进入页面时如何将ScrollView重置到顶部
React Navigation v4 没有内置useIsFocused钩子,可以通过监听导航生命周期的didFocus事件实现需求,分函数组件、类组件两种实现方式:
函数组件实现
如果你的页面组件可以直接拿到路由传入的navigation属性,直接在useEffect中添加事件监听即可:
import React, { useRef, useEffect } from 'react'; import { ScrollView } from 'react-native'; const ScrollPage = (props) => { const scrollViewRef = useRef(null); useEffect(() => { // 绑定页面聚焦监听事件 const focusListener = props.navigation.addListener('didFocus', () => { scrollViewRef.current?.scrollTo({ x: 0, y: 0, animated: true }); }); // 组件卸载时移除监听避免内存泄漏 return () => focusListener.remove(); }, [props.navigation]); return ( <ScrollView ref={scrollViewRef}> {/* 你的页面内容 */} </ScrollView> ); }; export default ScrollPage;
如果是深层嵌套的组件无法直接拿到navigation属性,使用react-navigation提供的withNavigation高阶组件包裹即可:
// 新增导入 import { withNavigation } from 'react-navigation'; // 导出时包裹组件 export default withNavigation(ScrollPage);
类组件实现
类组件在生命周期钩子中绑定/移除监听即可:
import React, { Component } from 'react'; import { ScrollView } from 'react-native'; import { withNavigation } from 'react-navigation'; class ScrollPage extends Component { scrollViewRef = null; componentDidMount() { this.focusListener = this.props.navigation.addListener('didFocus', () => { this.scrollViewRef?.scrollTo({ x: 0, y: 0, animated: true }); }); } componentWillUnmount() { this.focusListener.remove(); } render() { return ( <ScrollView ref={ref => this.scrollViewRef = ref}> {/* 你的页面内容 */} </ScrollView> ); } } export default withNavigation(ScrollPage);
注意:React Navigation v4的页面聚焦事件名为
didFocus,不要和v5/v6版本的focus事件名混淆。
内容的提问来源于stack exchange,提问作者Daniel Corona
相关产品推荐
相关产品推荐

