如何从 stack.navigation 之外的组件使用 navigation.navigate [英] How to use navigation.navigate from a component outside the stack.navigation
问题描述
我有一个使用 React Native 的应用程序,其中我使用的是 react-navigation (5.2.9).
I have an application using React native where I am using react-navigation (5.2.9).
我在我的屏幕上构建了一个 Stack.Navigator,但我希望页脚组件在外面,以便它在所有屏幕中呈现.问题是,我无法从页脚导航,这是我需要做的,因为页脚有几个按钮应该改变屏幕:
I built a Stack.Navigator where I've got my screens but I want the Footer component to be outside so it renders in all screens. The problem is, I can't navigate from the footer, which is what I need to do as the footer has a few buttons that should be changing the screen:
const Stack = createStackNavigator();
const App = () => {
return (
<Provider store={store}>
<NavigationContainer>
<Header />
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
headerShown: false
}}
/>
<Stack.Screen
name="Login"
component={LoginScreen}
options={{
headerShown: false
}}
/>
</Stack.Navigator>
<Footer />
</NavigationContainer>
</Provider>
);
};
如何将导航道具传递给页脚组件?
How do I pass the navigation prop to the footer component?
推荐答案
试试这个:
创建一个名为:RootNavigation.js 的新文件
Create a new file named: RootNavigation.js
// RootNavigation.js
import * as React from 'react';
export const navigationRef = React.createRef();
export function navigate(name, params) {
navigationRef.current?.navigate(name, params);
}
// file where you have the navigation
import {navigationRef} from './path/to/RootNavigation';
<NavigationContainer ref={navigationRef}>
.....
<Footer />
</NavigationContainer>
Footer.js 应该是这样的:
And Footer.js should be something like this:
// Footer.js
import React from 'react';
import {View, Button} from 'react-native';
import * as RootNavigation from './path/to/RootNavigation';
const Footer= () => {
return (
<View>
<Button
title={'Go to'}
onPress={() =>
RootNavigation.navigate('screenName ', {userName: 'Lucy'})
}
/>
</View>
);
};
export default Footer;
有关更多信息,您可以阅读文档.https://reactnavigation.org/docs/navigating-without-navigation-prop/一个>
For more info you can read the documentation. https://reactnavigation.org/docs/navigating-without-navigation-prop/
这篇关于如何从 stack.navigation 之外的组件使用 navigation.navigate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!