【问题标题】:React and Flowtype - inherit classReact 和 Flowtype - 继承类
【发布时间】:2018-09-18 11:29:03
【问题描述】:
假设我有
// Foo.js
type PropsType = { cool: boolean };
class Foo extends React.Component<PropsType> {}
// Bar.js
import Foo from './Foo';
type PropsBar = { temp: string };
class Bar extends Foo {
test() {
this.props.cool; // there is no error
this.props.temp;
^^^^ Property not found in object type
}
}
我的问题是,如何将额外的Props 传递给Bar 组件?
【问题讨论】:
标签:
javascript
reactjs
typescript
flowtype
【解决方案1】:
你需要让你的超类通用。正如React.Component 是通用的一样,您的类和函数也可以是通用的。
您可以通过引入类型参数来进行类或函数等泛型声明。
让我们将Foo 设为通用
export default class Foo<T> extends React.Component<FooProps & T> {}
注意交集类型,写成FooProps & T,它传递给通用超类React.Component。这意味着Foo.prototype.props 将具有FooProps 中声明的属性以及T 中声明的任何属性。
现在当我们使用Foo 时,例如在extends 子句中,我们需要为T 指定一个类型。
type BarProps = { temp: string };
export default class Bar extends Foo<BarProps> {
constructor(props, context) {
super(props, context);
console.log(this.props.temp);
}
}
如果您想保持Foo 的使用者的简单性,不添加额外的道具,您可以为T 指定一个默认类型,如
export default class Foo<T = {}> extends React.Component<FooProps & T> {}
export class Bar extends Foo {}
注意:以上所有语法在 Flow 和 TypeScript 中都有效。