React-Navigation v5中的Typescript StackNavigatonProps和Screen道具

时间:2020-03-16 10:34:18

标签: typescript react-native react-navigation expo

当屏幕位于路由器的不同文件中时,为屏幕的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

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

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