【问题标题】:Set stack navigator initialRouteName based on tab根据选项卡设置堆栈导航器 initialRouteName
【发布时间】:2020-11-07 10:34:06
【问题描述】:

我有一个如下标签导航器

export const MainNavigator = () => {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" options={{ title: "Home" }} component={MainStackScreen} />
      <Tab.Screen name="Favorite" options={{ title: "Favorite" }} component={MainStackScreen} />
    </Tab.Navigator>
  );
};

(简化的)MainStackScreen 如下所示:

export const MainStackScreen = () => {
  return (
    <Stack.Navigator screenOptions={{ headerBackTitleVisible: false }}>
      <Stack.Screen name="Home" component={HomeScreen} />
      <Stack.Screen name="Favorite" component={FavoriteHomeScreen} />
      <Stack.Screen name="Organisation" component={OrganisationScreen}/>
      <Stack.Screen name="Leagues" component={LeaguesScreen}/>
      <Stack.Screen name="Groupes" component={GroupesScreen}/>
    </Stack.Navigator>
  );
};

基本上,我希望有一个不同的 initialRouteName,具体取决于选择的选项卡。

为了提供更多上下文,最喜欢的选项卡允许用户跳过您在主页选项卡上的一些导航步骤,但让用户导航到相同的屏幕。这就是这两个选项卡共享同一个堆栈的原因。

【问题讨论】:

    标签: typescript react-native react-navigation


    【解决方案1】:

    你可以这样做:

    const MainStackScreen = ({route}) => {
      return (
        <Stack.Navigator
          initialRouteName={route.name === 'Favorite' ? 'Leagues' : 'Home'}
          screenOptions={{headerBackTitleVisible: false}}>
          <Stack.Screen name="Favorite" component={FavoriteHomeScreen} />
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Organisation" component={OrganisationScreen} />
          <Stack.Screen name="Leagues" component={LeaguesScreen} />
          <Stack.Screen name="Groupes" component={GroupesScreen} />
        </Stack.Navigator>
      );
    };
    

    根据当前路由名称(HomeFavorite 在您的情况下),您可以动态设置 initialRouteName

    在上面的示例中,如果您在Favorite 标签上,initialRouteName 将为Leagues,否则为Home


    如果您只想跳到 Home 堆栈(如果您在 Home 选项卡上,并且如果您在 Favorite 选项卡上跳到 Favorite 堆栈,则不要'不需要三元语句,你可以这样做:

    // ...
    initialRouteName={route.name}
    // ...
    

    【讨论】:

    • 不需要额外的参数。可以只使用 route.name 来获取选项卡的名称
    • @satya164 例如,如果您想从主页选项卡转到主页堆栈,这是正确的,但这更灵活。例如,如果您使用的是Favorite,则可以跳至Leagues。但我会将您的观点添加到答案中。
    • 我不是说initialRouteName={route.name},而是在组件内部根据route.name有条件地设置initialRouteName,而不是传递额外的参数
    • @satya164 感谢您指出这一点。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    相关资源
    最近更新 更多