反应本机嵌套导航-单击父抽屉路径时返回堆栈导航器的初始路径

时间:2019-02-01 19:48:03

标签: react-native react-navigation react-navigation-stack react-navigation-drawer

我在我的本机项目中使用以下导航设置。这里我使用抽屉导航和堆栈导航。

import MainScreen from '../components/MainScreen';
import SettingsScreen from '../components/SettingsScreen';
import FriendsListScreen from '../components/FriendsListScreen';
import FriendProfileScreen from '../components/FriendProfileScreen';

// stack navigator - 1
const MainScreenStack = createStackNavigator(
    {
        MainScreen: MainScreen,
        FriendsListScreen: FriendsListScreen,
        FriendProfileScreen: FriendProfileScreen,
    },
    {
        initialRouteName: 'MainScreen',
        navigationOptions: {
            drawerLabel: "Home"
        },
    }
);

// stack navigator - 2
const SettingsScreenStack = createStackNavigator(
    {
        SettingsScreen: SettingsScreen
    },
    {
        navigationOptions: {
            drawerLabel: "Settings"
        },
    }
);

// drawer navigation (stack navigator 1 + 2)
const AppNavigator = DrawerNavigator({
  MainScreen: MainScreenStack,
  SettingsScreen: SettingsScreenStack
});

const AppContainer = createAppContainer(AppNavigator)

场景:

  • 从抽屉中,我单击“主页”链接并导航到MainScreen。
  • 在主屏幕上,我单击一个按钮,然后导航到FriendsListScreen。
  • 从FriendsListScreen,我再次打开抽屉并单击“主页”链接。抽屉关闭并且没有导航。

模型:

enter image description here enter image description here enter image description here

当我从抽屉中单击“主页”链接时,是否可以导航回主屏幕?

1 个答案:

答案 0 :(得分:0)

我通过创建如下的自定义抽屉内容来解决此问题:

import {DrawerItems, SafeAreaView, createStackNavigator, createDrawerNavigator, createAppContainer} from "react-navigation";

const DrawerContent = (props) => (
  <ScrollView>
    <SafeAreaView forceInset={{top: 'always', horizontal: 'never'}}>
      <DrawerItems {...props} onItemPress={ ({route, focused}) => {
        if (route.key === "MainScreen") {
          if (route.routes.length === 1) {
            props.navigation.closeDrawer();
          } else {
            props.navigation.navigate(route.routes[0].routeName);
          }
        } else {
          props.onItemPress({route, focused});
        }
      }} />
    </SafeAreaView>
  </ScrollView>
);

const AppNavigator = DrawerNavigator({
  MainScreen: MainScreenStack,
  SettingsScreen: SettingsScreenStack
}, {contentComponent: DrawerContent});