使用react-navigation v4 an,您可以将ScrollView 滚动到屏幕焦点顶部:
import React, {useEffect} from 'react';
import {View, Button, ScrollView} from 'react-native';
export default function Screen1({navigation}) {
const scrollViewRef = React.createRef();
useEffect(() => {
const focusListener = navigation.addListener('didFocus', () => {
scrollViewRef?.current?.scrollTo({x: 0, y: 0, animated: true});
});
return () => focusListener.remove();
}, [navigation, scrollViewRef]);
return (
<View>
<Button
title={'Go to screen 2'}
onPress={() => navigation.navigate('screen2')}
/>
<ScrollView ref={scrollViewRef}>
<View
style={{
height: 300,
borderWidth: 1,
marginHorizontal: 15,
marginTop: 10,
}}
/>
<View
style={{
height: 600,
borderWidth: 1,
marginHorizontal: 15,
marginTop: 10,
}}
/>
<View
style={{
height: 200,
borderWidth: 1,
marginHorizontal: 15,
marginTop: 10,
}}
/>
</ScrollView>
</View>
);
}
基本思路是:
- 创建
ref 并将其分配给ScrollView
- 添加
react-navigation提供的didFocus监听器
- 使用
scrollViewRef?.current?.scrollTo({x: 0, y: 0, animated: true}); 将ScrollView 滚动到顶部