如何从 react-navigation 标签栏调用 scrollTo 函数
How to call scrollTo function from react-navigation tab bar
我创建了一个函数,它在调用时将 ScrollView 滚动到设定位置(靠近顶部)。我希望从 react-navigation
选项卡栏调用该函数。调用函数很容易,但我很难让它与屏幕组件的 scrollRef 通信。
这是我的点心:https://snack.expo.dev/@dazzerr/scroll-to-top-function
你会在 App.js 中找到这个函数,它在按下标签栏时被调用:
const onTabPress = () => {
scrollRef.current?.scrollTo({ // how do I get ref={scrollRef} from component.js ScrollView?
y: 0,
animated: true,
});
};
并且在 component.js 中是有问题的 ScrollView:
<ScrollView
ref={scrollRef}
style={styles.container}
scrollEventThrottle={16}
>
{ScreenContent()}
</ScrollView>
如何从 app.js 的 onTabPress 函数内部调用 component.js 获取 scrollRef?
您需要像这样通过 react-navigation setParams 传递函数:
这会进入您的 createBottomTabNavigator
:
tabBarOnPress: (scene, jumpToIndex) => {
scene.navigation.state.params.scrollToTop(); // Here's the magic!
},
这在你的 component
里:
useEffect(() => {
props.navigation.setParams({
scrollToTop: () => {
onTabPress();
},
});
}, []);
const onTabPress = () => {
scrollRef.current?.scrollTo({
y: 600, // whatever number you want here
animated: true,
});
};
当然不要忘记将 scrollRef
添加到您的 ScrollView,并确保您的 ScrollView 来自 react-native 而不是 react-navigation。您可能还想在 tabBarOnPress
中添加条件,例如:
if (
isFocused &&
typeof route.routes[0]?.params?.onTabBarPress !== "function"
)
但那是你做的
我创建了一个函数,它在调用时将 ScrollView 滚动到设定位置(靠近顶部)。我希望从 react-navigation
选项卡栏调用该函数。调用函数很容易,但我很难让它与屏幕组件的 scrollRef 通信。
这是我的点心:https://snack.expo.dev/@dazzerr/scroll-to-top-function
你会在 App.js 中找到这个函数,它在按下标签栏时被调用:
const onTabPress = () => {
scrollRef.current?.scrollTo({ // how do I get ref={scrollRef} from component.js ScrollView?
y: 0,
animated: true,
});
};
并且在 component.js 中是有问题的 ScrollView:
<ScrollView
ref={scrollRef}
style={styles.container}
scrollEventThrottle={16}
>
{ScreenContent()}
</ScrollView>
如何从 app.js 的 onTabPress 函数内部调用 component.js 获取 scrollRef?
您需要像这样通过 react-navigation setParams 传递函数:
这会进入您的 createBottomTabNavigator
:
tabBarOnPress: (scene, jumpToIndex) => {
scene.navigation.state.params.scrollToTop(); // Here's the magic!
},
这在你的 component
里:
useEffect(() => {
props.navigation.setParams({
scrollToTop: () => {
onTabPress();
},
});
}, []);
const onTabPress = () => {
scrollRef.current?.scrollTo({
y: 600, // whatever number you want here
animated: true,
});
};
当然不要忘记将 scrollRef
添加到您的 ScrollView,并确保您的 ScrollView 来自 react-native 而不是 react-navigation。您可能还想在 tabBarOnPress
中添加条件,例如:
if (
isFocused &&
typeof route.routes[0]?.params?.onTabBarPress !== "function"
)
但那是你做的