react-navigation v5 中的 Typescript StackNavigatonProps 和 Screen 道具

Posted

技术标签:

【中文标题】react-navigation v5 中的 Typescript StackNavigatonProps 和 Screen 道具【英文标题】:Typescript StackNavigatonProps and Screen props in react-navigation v5 【发布时间】:2020-06-27 11:13:09 【问题描述】:

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

你可以试试这个:

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

【讨论】:

这个语法正确吗?我收到“逗号运算符的左侧未使用且没有副作用”错误

以上是关于react-navigation v5 中的 Typescript StackNavigatonProps 和 Screen 道具的主要内容,如果未能解决你的问题,请参考以下文章