问题
HomeStackNavigator(stack)
---HomeTabsNavigator(Tab)
---FirstTab(stack)
---CreatePost(screen)
---Posts(Tab)
---Following(screen)
---Feed(screen) <----- functional component in here, lets call it component1
---SecondTab
...
---Screen2
I want to be able to navigate from a functional component in the feed screen to screen 2. I've tried looking at the nested navigation docs in react native docs but no luck.
回答1:
You can use the RootNavigation approach: https://reactnavigation.org/docs/navigating-without-navigation-prop/
First you create a file at your directory root called RootNavigation.js
that looks like this:
import * as React from 'react';
export const navigationRef = React.createRef();
export function navigate(name, params) {
navigationRef.current?.navigate(name, params);
}
Then you pass the navigationRef
as a ref to your NavigationContainer
:
import * as RootNavigation from './RootNavigation';
// ...
<NavigationContainer ref={RootNavigation.navigationRef}>
<HomeStackNavigator />
</NavigationContainer>
This allows you to navigate from anywhere.
Then you can do something like this in your Feed
screen:
const Feed = () => {
// ...
<Button
title="Navigate to SecondTab"
onPress={() => RootNavigation.navigate('SecondTab')}
/>
// ...
};
来源:https://stackoverflow.com/questions/62941680/how-to-navigate-from-a-functional-component-from-a-screen-in-a-tab-navigator-w