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, {}> {}