React原生:如何设置React Navigation类型,这样我就不必在使用的每个组件上创建NavigationProps?

toiithl6  于 2022-12-30  发布在  React
关注(0)|答案(1)|浏览(110)
    • bounty将在6天后过期**。回答此问题可获得+50声望奖励。Vik希望引起更多人关注此问题。

所以现在我有一个routes. tsx文件保存我所有的类型。但是在使用useNavigation()的屏幕上,我总是需要在那个组件中为它创建一个类型。我如何正确地为我的路线设置一个全局类型,这样我就不必这样做了?
routes.tsx

export type AuthStackParamList = {
  Landing: undefined;
  GetStarted: undefined;
  VerifyOtp: { email: string };
  PrivacyPolicy: undefined;
  TermsOfService: undefined;
};

export type AppTabParamList = {
  HomeScreen: undefined;
  FriendsScreen: undefined;
  NotificationsScreen: undefined;
  SettingsScreen: undefined;
};

export type OnboardingStackParamList = {
  UsernameScreen: undefined;
};

export type HomeTabStackParamList = {
  Home: undefined;
};

export type FriendsTabStackParamList = {
  Friends: undefined;
  SearchUsers: undefined;
};

export type SettingsTabStackParamList = {
  Settings: undefined;
  EditName: { id: string; name: string };
  EditUsername: { id: string; username: string };
  DeleteAccount: undefined;
};

AuthStack.tsx

const AuthStack = createNativeStackNavigator<AuthStackParamList>();

export function AuthStackNavigator() {
  return (
    <AuthStack.Navigator
      initialRouteName="Landing"
      }}>
      <AuthStack.Screen
        name="Landing"
        component={LandingScreen}
        options={{ headerShown: false }}
      />
      <AuthStack.Screen
        name="GetStarted"
        component={GetStartedScreen}
        options={{ headerTitle: '' }}
      />
      <AuthStack.Screen
        name="VerifyOtp"
        component={VerifyOTPScreen}
        options={{ headerShown: false, gestureEnabled: false }}
      />
      <AuthStack.Screen
        name="TermsOfService"
        component={TermsOfServiceScreen}
        options={{ headerTitle: 'Terms of Service' }}
      />
      <AuthStack.Screen
        name="PrivacyPolicy"
        component={PrivacyPolicy}
        options={{ headerTitle: 'Privacy Policy' }}
      />
    </AuthStack.Navigator>
  );
}

GetStartedScreen.tsx
这就是我希望避免在需要点击useNavigation时必须执行的操作

type GetStartedScreenNavigationProps = NativeStackNavigationProp<
  AuthStackParamList,
  'GetStarted'
>;

const GetStartedScreen = () => {
  const navigation = useNavigation<GetStartedScreenNavigationProps>();
3qpi33ja

3qpi33ja1#

我认为没有办法做到这一点。因为useNavigation是一个钩子。而且钩子总是必须在任何组件内部创建。你不能创建钩子并将其导出到任何其他组件中使用。

相关问题