跳到主要内容
版本:7.x

使用 TypeScript 进行类型检查

React Navigation 可以配置为使用 TypeScript 对屏幕及其参数以及各种其他 API 进行类型检查。这在使用 React Navigation 时提供更好的 intelliSense 和类型安全性。

注意

React Navigation 旨在与 TypeScript 中的 strict 模式一起使用。如果您不使用 strict 模式,某些功能可能无法按预期工作。

使用静态 API 配置 TypeScript 需要 2 个步骤

  1. 每个屏幕组件都需要指定它接受的 route.params prop 的类型。StaticScreenProps 类型使其更简单

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

    type Props = StaticScreenProps<{
    username: string;
    }>;

    function ProfileScreen({ route }: Props) {
    // ...
    }
  2. 为根导航器生成 ParamList 类型,并将其指定为 RootParamList 类型的默认类型

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

    const HomeTabs = createBottomTabNavigator({
    screens: {
    Feed: FeedScreen,
    Profile: ProfileScreen,
    },
    });

    const RootStack = createNativeStackNavigator({
    screens: {
    Home: HomeTabs,
    },
    });

    type RootStackParamList = StaticParamList<typeof RootStack>;

    declare global {
    namespace ReactNavigation {
    interface RootParamList extends RootStackParamList {}
    }
    }

    这是类型检查 useNavigation hook 所必需的。

通常,我们建议使用 useNavigation prop 的默认类型,以便以与导航器无关的方式访问导航对象。但是,如果您需要使用导航器特定的 API,则需要手动注释 useNavigation

type BottomTabParamList = StaticParamList<typeof BottomTabNavigator>;
type ProfileScreenNavigationProp = BottomTabNavigationProp<
BottomTabParamList,
'Profile'
>;

// ...

const navigation = useNavigation<ProfileScreenNavigationProp>();

请注意,以这种方式注释 useNavigation 不是类型安全的,因为我们无法保证您提供的类型与导航器的类型匹配。

使用动态 API 嵌套导航器

考虑以下示例

const Tab = createBottomTabNavigator();

function HomeTabs() {
return (
<Tab.Navigator>
<Tab.Screen name="Feed" component={FeedScreen} />
<Tab.Screen name="Profile" component={ProfileScreen} />
</Tab.Navigator>
);
}

const RootStack = createStackNavigator({
Home: HomeTabs,
});

在这里,HomeTabs 组件是使用动态 API 定义的。这意味着当我们使用 StaticParamList<typeof RootStack> 为根导航器创建参数列表时,它不会知道嵌套导航器中定义的屏幕。要解决此问题,我们需要显式指定嵌套导航器的参数列表。

这可以通过使用屏幕组件接收的 route prop 的类型来完成

type HomeTabsParamList = {
Feed: undefined;
Profile: undefined;
};

type HomeTabsProps = StaticScreenProps<
NavigatorScreenParams<HomeTabsParamList>
>;

function HomeTabs(_: HomeTabsProps) {
return (
<Tab.Navigator>
<Tab.Screen name="Feed" component={FeedScreen} />
<Tab.Screen name="Profile" component={ProfileScreen} />
</Tab.Navigator>
);
}

现在,当使用 StaticParamList<typeof RootStack> 时,它将包含嵌套导航器中定义的屏幕。