小编典典

打字稿React:访问组件属性类型

reactjs

npm软件包@types/react允许我们在TypeScript应用程序内部使用React。我们将组件定义为

type Props = {...}

type State = {...}

export default class MyComponent extends React.Component<Props, State> {
}

在这里,我们必须声明组件属性和状态的类型(在类型变量中)。

在声明了这些类型之后,TypeScript将使用该类型来验证组件的用法(传递给它的道具的形状)。

我想围绕这样的组件创建一个容器。容器将重复使用组件的道具。但是,为了创建具有相同道具的另一个组件,我必须再次重新声明道具的类型。或从原始组件文件中导出它们并导入到容器中:

// original file
export type Props = {...}

// container file
import MyComponent, { Props } from './original'

但是我已经MyComponent从该文件导入了。该组件已经包含有关其消耗的道具的信息(感谢在中键入变量React.Component)。

问题是 如何在不显式导出/导入道具类型的情况下从组件类本身访问该信息

我想要类似的东西:

import MyComponent from './MyComponent'

type Props = MyComponent.Props // <= here access the component prop types

export default class MyContainer extends React.Component<Props, {}> {}

阅读 252

收藏
2020-07-22

共1个答案

小编典典

2019 :注意到上面的所有答案都已经过时了,所以这里是一个新鲜的答案。


查询类型

使用较新的TS版本,您可以使用查找类型。

type ViewProps = View['props']

尽管非常方便,但这 仅适用于类组件


React.ComponentProps

React typedef附带了一个实用程序,可从任何组件中提取道具的类型。

type ViewProps = React.ComponentProps<typeof View>

type InputProps = React.ComponentProps<'input'>

这有点冗长,但是与类型查找解决方案不同:

  • 开发人员的意图更加明确
  • 这将与功能组件和类组件一起使用

所有这些使该解决方案成为 最可靠的 解决方案:如果您决定从类迁移到挂钩,则无需重构任何客户端代码。

2020-07-22