javascript - 如何创建使用react-navigation泛型的新泛型对象类型?

标签 javascript reactjs typescript react-native types

在我的 React Native 项目中,我有多个屏幕,我必须在每个屏幕上一遍又一遍地导入这些类型并设置为屏幕中的 props 类型。

import { RouteProp } from '@react-navigation/native'
import { StackNavigationProp } from '@react-navigation/stack'

import { NavigatorParameters } from '../references/types/navigators'

type PropsType = {
  navigation: StackNavigationProp<NavigatorParameters, 'ChangeData'>,
  route: RouteProp<NavigatorParameters, 'ChangeData'>
}

function ChangeData({ navigation, route }: PropsType) {

可以更简化为这样吗?因此我只能导入一种类型

import ScreenPropsPatternType from '../references/types/screen-props-pattern'

function ChangeData({ navigation, route }: ScreenPropsPatternType<'ChangeData'>) {

最佳答案

React 导航库提供 a generic type already for this exact purpose :

Alternatively, you can also import a generic type to define types for both the navigation and route props from the corresponding navigator:

就您而言,它看起来像这样:

import { StackScreenProps } from '@react-navigation/stack';
import { NavigatorParameters } from '../references/types/navigators'

type PropsType = StackScreenProps<NavigatorParameters, 'ChangeData'>;

function ChangeData({ navigation, route }: PropsType) {

如果您想进一步简化它,您可以包装它并导出您自己的类型。请参阅Generic Object Types documentation有关其工作原理的更多详细信息。

import { StackScreenProps } from '@react-navigation/stack';
import { NavigatorParameters } from '../references/types/navigators'

export type ScreenPropsPatternType<K extends keyof NavigatorParameters> =
  StackScreenProps<NavigatorParameters, K>;

因此您可以在屏幕组件中轻松使用它。

import { ScreenPropsPatternType } from '../references/types/screen-props-pattern';

type PropsType = ScreenPropsPatternType<'ChangeData'> & {
  // If you have any other custom props, this is totally optional.
  customProp: number;
}

function ChangeData({ navigation, route, customProp }: PropsType) {

关于javascript - 如何创建使用react-navigation泛型的新泛型对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68659655/

相关文章:

css - 如何增加 Angular 8 中 mat-dialog-actions 的宽度

typescript - VS-Code 提示访问器但针对 ES6

javascript - 如果对象函数存在于 TypeScript 中,则调用它

ReactJS aws 被 CORS 预检策略阻止

javascript - HTML:JavaScript:阻止表单提交和调用 Javascript 函数

javascript - 通过过滤未定义计算对象数组的平均值

javascript - 基于条件语句的背景不透明度变化不适用于移动设备

reactjs - 在 Enzyme 测试中更改 MemoryRouter 中的路由路径

reactjs - 如何更改 react 选择上的下拉指示器位置

javascript - 在单击按钮时调整 div 的大小,这应该使用 AJAX 完成吗?