How to Navigate from a functional component, from a screen in a tab navigator, where that tab navigator is nested in a parent stack navigator

ε祈祈猫儿з 提交于 2020-12-27 06:33:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!