javascript - React 和 Flowtype - 继承类

标签 javascript reactjs typescript flowtype

假设我有

// 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/

相关文章:

javascript - 将 div 拆分为每个 div 具有最大高度的 div

javascript - 查找文本节点内滴的确切位置

javascript - 如何将这个原型(prototype)函数转换成es6?

c# - 在 HTML 页面中加载资源的 JS 或任何其他语言 Hook

javascript - 嵌套数组如果值相等则将对象添加到状态数组

javascript - React+Next.js+Firebase :Auth URL changes to username and password after signInWithEmailAndPassword

TypeScript 属性装饰器 : access to other properties

javascript - 为每个类单独继承静态成员

node.js - 错误 [ERR_REQUIRE_ESM] : require() of ES Module - Vue 3 Typescript

javascript - 即使在服务器和客户端上设置 header 后,请求的资源上仍存在错误 "No ' Access-Control-Allow-Origin' header