首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >flowtype:继承和泛型

flowtype:继承和泛型
EN

Stack Overflow用户
提问于 2017-10-17 15:16:31
回答 1查看 402关注 0票数 0

我想继承一个React组件,并定义新的Props。类似这样的东西( Bar有很多错误,应该是完全错误的):

代码语言:javascript
复制
// @flow

class Component<Props> {
    props: Props;

    constructor(props: Props) {
        this.props = props;
    }
}

type FooProps = {
    x: number;
}

class Foo extends Component<FooProps> {
    _render(value: string) {
        return `hello, ${value}`;
    }
    render() {
        return this._render(`${this.props.x}`);
    }
};

type BarProps = {
    x: number;
    y: number;
}

class Bar extends Foo<BarProps> {
    render() {
        return this._render(`${this.props.x} ${this.props.y}`);
    }
}

const foo: Foo = new Foo({x: 1});
const bar: Bar = new Bar({x: 1, y: 2});

我应该如何在继承中使用流泛型?(在React组件的上下文中,如果重要的话)。

使用flow 0.57.2和react 16.0.0

EN

回答 1

Stack Overflow用户

发布于 2017-10-17 15:37:35

最简单的情况是,在ES中创建一个新的react组件并键入props如下所示:

代码语言:javascript
复制
// @flow
import React from 'react'

type Props = { books: Array<String>, search: (string) => void }

class SearchList extends React.Component {
  static defaultProps: Props
  props: Props

  render () { /*...*/ }
}

SearchList.defaultProps = { books: [], search: (_) => undefined }

编辑:忘记提到这是使用阶段3中的class fields建议。如果您使用的是像create-react-app这样的引导程序,则可以使用它。否则,您可以执行以下操作:

代码语言:javascript
复制
// @flow
import React from 'react'

type Props = { books: Array<String>, search: (string) => void }

class SearchList extends React.Component<Props> {      
  render () { /*...*/ }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46784510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档