React Navigation 用 BottomTabs 注释 useNavigator

React Navigation annotating useNavigator with BottomTabs

任何人都可以使用 RootStack -> 选项卡 -> 每个选项卡都有一个堆栈设置来帮助输入/注释 useNavigator

import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import type {
  CompositeScreenProps,
  NavigatorScreenParams,
} from '@react-navigation/native';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { BottomTabScreenProps } from '@react-navigation/bottom-tabs';

export type RootStackParamList = {
  Home: NavigatorScreenParams<HomeTabParamList>;
};

export type RootStackScreenProps<T extends keyof RootStackParamList> =
  NativeStackScreenProps<RootStackParamList, T>;

export type HomeTabParamList = {
  Dashboard: undefined;
  Map: undefined;
};

export type HomeTabScreenProps<T extends keyof HomeTabParamList> =
  CompositeScreenProps<
    BottomTabScreenProps<HomeTabParamList, T>,
    RootStackScreenProps<keyof RootStackParamList>
  >;

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

export default () =>
  useNavigation<NativeStackNavigationProp<RootStackParamList>>();
const navigation = useNavigator()
navigation.navigate('Dashboard') // Throws type error, only 'Home' is a suggestion.

你需要这样使用它:

navigation.navigate('Home', { screen: 'Dashboard' })

https://reactnavigation.org/docs/nesting-navigators/#navigating-to-a-screen-in-a-nested-navigator

您也不需要 export default () => useNavigation<NativeStackNavigationProp<RootStackParamList>>();。如果您从 @react-navigation/native 导入 useNavigation,它将具有正确的类型。