react-navigation v5 中的 Typescript StackNavigatonProps 和 Screen 属性

问题描述 投票:0回答:2

当屏幕与路由器位于不同的文件中时,定义屏幕的

navigation
属性的最佳方法是什么?假设我有一个文件,我在其中定义了路线:

//Router.tsx

type RootStackParamList = {
  Home: undefined;
  Profile: undefined;
}

const Stack = createStackNavigator<RootStackParamList>();

// Component rendering navigator
const Router = () => {
   .
   .
   .
}

然后我有单独的屏幕文件:

// Home.tsx


// here has to be the same RootStackParamList
// that we've already defined in Router.tsx
type = HomeScreenNavigationProp = StackNavigationProp<
  RootStackParamList,
  "Home"
>;

type Props: {
  navigation: HomeScreenNavigationProp
}


const Home = ({navigation}: Props) => {
  .
  .
  .
}

我是否必须一遍又一遍地将

RootStackParamList
复制到每个屏幕或创建类似
types.ts
文件并从那里导入它?有没有更好的方法来处理呢?我几乎在每个组件中都使用
navigation

typescript react-native react-navigation expo
2个回答
3
投票

你可以试试这个:

type RootStackComponent<RouteName extends keyof RootStackParamList> = React.FC<{
  navigation: StackNavigationProp<RootStackParamList, RouteName>,
  route: RouteProp<RootStackParamList, RouteName>
}>
const Home: RootStackComponent<'Home'> = ({ navigation, route }) => {}

0
投票

首先像这样定义你的 createStackNavigator 类型:

export type RootStackParamList = {
     Home: undefined;
     Register: undefined;
     Login: undefined;
};
const Stack = createStackNavigator<RootStackParamList>();

然后转到 Home.tsx 组件并添加以下行:

type Props = StackScreenProps<RootStackParamList, 'Home'>;

const Home = ({navigation, route}: Props) => {
 .
 .
 . 
} 

参考:https://reactnavigation.org/docs/typescript/

© www.soinside.com 2019 - 2024. All rights reserved.