定义'导航'的更好方法对象,当在React Native中使用堆栈导航器时
使用React-Navigation时,我在模块化中遇到了一些麻烦。
我的问题是: “ nofollow noreferrer”> react navigation doc tocescript部分建议为每个屏幕prop创建类型的类型:
//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'>;
因此,基本上,基本上,,,,基本上,,,,,,,基本上,,,,,,基本上,,,,,,那么,基本上,,,,,,那么,基本上,,,,,,基本上,,,,那么,基本上,,,,,,基本上,,,那么,基本上,,,,基本上,,,,那么,基本上,基本上导入 nativestackscreenprops 类型,并将 rootstackParamlist 和页名传递为字符串。
但是,如果我必须在同一堆栈中为另一个页面(例如Home 页面)定义Prop类型,那么据我所知,我将不得不重复相同的两种类型的导入,这不是理想的。
所有的更改是字符串(“配置文件”,“ home”等)传递到类型中。
// Home.tsx
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import type { RootStackParamList } from './types';
type HomeProps = NativeStackScreenProps<RootStackParamList, 'Home'>;
我是TS的初学者,所以我的问题是:如何创建一个通用类型,可以帮助我避免在每个页面上使用相同的两个导入?由于这两种道具类型之间的唯一变化是字符串。
I'm having some trouble with modularization for the prop types, when using react-navigation.
My problem is:
The React Navigation doc Typescript section suggests creating the types for each screen props like so:
//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.
But if I had to define prop types for another page in the same Stack, e.g. the Home page, I would have to repeat the SAME two type imports, which is not ideal, as far as I know.
All that changes is the string ('Profile', 'Home', etc) passed into the type.
// 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? Since the only thing changing between these two prop types is a string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以将RootstackParamList抽象并将其放入单独的文件中。并导出类似于下面的通用类型:
并以此方式使用它:
You can abstract RootStackParamList and put it in a separate file. and export a generic type like below:
And use it like this: