【问题标题】:How to compose ParamList for nested navigators in v5?如何在 v5 中为嵌套导航器编写 ParamList?
【发布时间】:2020-07-04 15:03:39
【问题描述】:

假设我有两个这样的导航器:

export type RootStackParamList = {
  Bootstrap: undefined;
  Login: undefined;
  MainApp: undefined;
};

export type MainTabsParamList = {
  Explore: undefined;
  Profile: undefined;
};

const MainTabs = createBottomTabNavigator<MainTabsParamList>();
const MainApp = () => (
  <MainTabs.Navigator >
    <MainTabs.Screen
      name="Explore"
      component={Explore}
    />
    <MainTabs.Screen
      name="Profile"
      component={Profile}
    />
  </MainTabs.Navigator>
);

const RootStack = createStackNavigator<RootStackParamList>();
const App = () => {
  return (
    <NavigationContainer>
      <RootStack.Navigator initialRouteName="Bootstrap" headerMode="none">
        <RootStack.Screen name="Bootstrap" component={Bootstrap} />
        <RootStack.Screen name="Login" component={Login} />
        <RootStack.Screen name="MainApp" component={MainApp} />
      </RootStack.Navigator>
    </NavigationContainer>
  );
};

现在,如果我想从 Bootstrap 屏幕导航到 Profile 屏幕。我必须写:(正确注释的导航道具)

navigation.navigate('MainApp', {screen: 'Profile'})

但是打字稿在这里给出错误。说Type '{ screen: string; }' is not assignable to type 'undefined'。这是因为 typescript 不知道 MainApp 有子屏幕。所以我必须以某种方式编写ParamLists,以便打字稿了解子屏幕。我怎么做? react-navigation v5 支持吗?

【问题讨论】:

    标签: typescript react-native react-navigation


    【解决方案1】:

    看起来没有开箱即用的解决方案,但找到了这个thread (issue)。在那里我们可能会找到好的solution

    type NestedNavigatorParams<ParamList> = {
      [K in keyof ParamList]: undefined extends ParamList[K]
        ? { screen: K; params?: ParamList[K] }
        : { screen: K; params: ParamList[K] }
    }[keyof ParamList]
    

    使用非常简单:

    export type MainTabsParamList = {
      Explore: undefined;
      Profile: undefined;
    };
    
    export type RootStackParamList = {
      Bootstrap: undefined;
      Login: undefined;
      MainApp: NestedNavigatorParams<MainTabsParamList>;
    };
    

    【讨论】:

    • 感谢 github 问题中缺少的澄清用法示例?
    【解决方案2】:

    2022 年 2 月 15 日更新:看起来现在有一个开箱即用的解决方案:D

    import { NavigatorScreenParams } from '@react-navigation/native';
    
    export type RootStackParamList = {
      Bootstrap: undefined;
      Login: undefined;
      MainApp: NavigatorScreenParams<MainTabsParamList>;
    };
    
    export type MainTabsParamList = {
      Explore: undefined;
      Profile: undefined;
    };
    

    查看文档:https://reactnavigation.org/docs/typescript/#type-checking-screens-and-params-in-nested-navigator

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 2021-12-23
      • 2021-01-21
      • 2021-06-27
      • 2020-10-22
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多