假设我有
// 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
组件?
最佳答案
您需要使您的父类(super class)变得通用。正如 React.Component
是通用的一样,您的类和函数也可以是通用的。
您可以通过引入类型参数来声明类或函数泛型。
让我们使 Foo
通用
export default class Foo<T> extends React.Component<FooProps & T> {}
注意交集类型,写作FooProps & T
,它被传递给通用父类(super class)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
的使用者的简单性而不添加额外的 props,您可以为 T
指定默认类型,如下所示
export default class Foo<T = {}> extends React.Component<FooProps & T> {}
export class Bar extends Foo {}
注意:上面的所有语法在 Flow 和 TypeScript 中都有效。
关于javascript - React 和 Flowtype - 继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453518/