[英]Better way of defining types for 'navigation' object, when using Stack Navigator in React Native
I'm having some trouble with modularization for the prop types, when using react-navigation.使用 react-navigation 时,我在道具类型的模块化方面遇到了一些麻烦。
My problem is: The React Navigation doc Typescript section suggests creating the types for each screen props like so:我的问题是: React Navigation 文档 Typescript 部分建议为每个屏幕道具创建类型,如下所示:
//types.ts
export type RootStackParamList = {
Home: undefined;
Profile: { userId: string };
Feed: { sort: 'latest' | 'top' } | undefined;
};
// Profile.tsx
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { RootStackParamList } from './types';
type ProfileProps = NativeStackScreenProps<RootStackParamList, 'Profile'>;
So, basically, importing the NativeStackScreenProps type, and passing both the RootStackParamList , and the page name, as a string.因此,基本上,导入NativeStackScreenProps类型,并将RootStackParamList和页面名称作为字符串传递。
But if I had to define prop types for another page in the same Stack, eg the Home page, I would have to repeat the SAME two type imports, which is not ideal, as far as I know.但是,如果我必须为同一个 Stack 中的另一个页面(例如主页)定义 prop 类型,我将不得不重复 SAME 两种类型的导入,据我所知,这并不理想。
All that changes is the string ('Profile', 'Home', etc) passed into the type.所有更改都是传递给类型的字符串('Profile'、'Home' 等)。
// Home.tsx
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { RootStackParamList } from './types';
type HomeProps = NativeStackScreenProps<RootStackParamList, 'Home'>;
I'm kind of a beginner with TS, so my question is: How can I create a generic type that could help me avoid using the same two imports on every page?我是 TS 的初学者,所以我的问题是:如何创建一个通用类型来帮助我避免在每个页面上使用相同的两个导入? Since the only thing changing between these two prop types is a string.
因为这两种道具类型之间唯一发生变化的是字符串。
You can abstract RootStackParamList and put it in a separate file.您可以抽象 RootStackParamList 并将其放在一个单独的文件中。 and export a generic type like below:
并导出如下的通用类型:
export type RootStackProps<T extend keyof RootStackParamList> = NativeStackScreenProps<RootStackParamList, T>;
And use it like this:并像这样使用它:
type HomeProps = RootStackProps<'Home'>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.