【问题标题】:typescript inferface for react navigation用于反应导航的打字稿界面
【发布时间】:2022-08-24 16:59:22
【问题描述】:

我真的不明白如何设置正确的类型来响应导航。

我有一个大堆栈一个屏幕,有时,有嵌套堆栈之类的家庭堆栈这也是一堆屏幕。 这里设置只是一个简单的屏幕,而不是堆栈。

<Stack.Screen name={AppStackRoutes.HomeStack} component={HomeStack} />
<Stack.Screen name={AppStackRoutes.Settings} component={SettingsScreen} />

我有两种导航的可能性:

  • 当我想导航到堆栈并指定屏幕并传递参数时:
navigate(AppStackRoutes.HomeStack, { screen: \'Home\', userProfile } );
  • 当我的屏幕是单独的并且我只想传递参数时:
navigate(AppStackRoutes.Settings, { userProfile } );

如何获取我的 NewScreenProps 界面?

const NewScreen = ({
  navigation: {
    navigate,
    openDrawer,
    closeDrawer,
    isFocused,
  },
}: NewScreenProps)

有我的界面,我不知道如何获得正确的导航类型:

export interface NewScreenProps {
  navigation: 
    {
      navigate: (
        route: AppStackRoutes, 
        params: ?,
      ) => void;
      openDrawer: () => void;
      [...]
    }
}

标签: reactjs typescript react-native react-navigation


【解决方案1】:

根据 react-navigation https://reactnavigation.org/docs/typescript/#type-checking-screens 提供的文档

要对屏幕进行类型检查,我们需要对屏幕接收到的导航道具和路线道具进行注释。 React Navigation 中的 navigator 包导出一个泛型类型,以从相应的 navigator 定义 navigation 和 route props 的类型。

例如,您可以将 NativeStackScreenProps 用于 Native Stack Navigator。

import type { NativeStackScreenProps } from '@react-navigation/native-stack';

type RootStackParamList = {
  Home: undefined;
  Profile: { userId: string };
  Feed: { sort: 'latest' | 'top' } | undefined;
};

type Props = NativeStackScreenProps<RootStackParamList, 'Profile'>;

这允许我们键入检查路线名称和您正在使用导航、推送等导航的参数。当前路线的名称对于键入检查 route.params 中的参数以及调用 setParams 时是必需的。

然后你可以使用上面定义的 Props 类型来注释你的组件。

function ProfileScreen({ route, navigation }: Props) {
  // ...
}

【讨论】:

    猜你喜欢
    • 2020-11-20
    • 2020-11-11
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2020-08-21
    • 2020-07-28
    相关资源
    最近更新 更多