【发布时间】:2017-08-31 01:01:49
【问题描述】:
npm 包@types/react 允许我们在 TypeScript 应用程序中使用 React。
我们将组件定义为
type Props = {...}
type State = {...}
export default class MyComponent extends React.Component<Props, State> {
}
这里我们必须为组件的 props 和 state 声明类型(在类型变量中)。
在我们声明了这些类型之后,TypeScript 使用它来验证我们组件的使用情况(传递给它的 props 的形状)。
我想围绕这样的组件创建一个容器。容器将重用组件的 props。但是为了创建另一个具有相同道具的组件,我必须再次重新声明道具的类型。或者从原始组件文件中导出并导入到容器中:
// original file
export type Props = {...}
// container file
import MyComponent, { Props } from './original'
但我已经从该文件中导入了MyComponent。这个组件已经包含了它使用的 props 的信息(感谢React.Component 中的类型变量)。
问题是如何在不显式导出/导入 props 类型的情况下从组件类本身访问该信息?
我想要类似的东西:
import MyComponent from './MyComponent'
type Props = MyComponent.Props // <= here access the component prop types
export default class MyContainer extends React.Component<Props, {}> {}
【问题讨论】:
-
嗨。从 2019 年开始,您应该更愿意使用此解决方案。其他人可以工作,但不是最新的和面向未来的解决方案:stackoverflow.com/a/55005902/82609
标签: reactjs typescript