Flowtype:基于类型提示类的HOC组件

Sve*_*ert 2 javascript reactjs flowtype

我正在尝试键入一个HOC,它为传递的Component添加一个prop,如下所示:

// @flow
import React, { Component } from 'react';
import type { ComponentType } from 'react';

type Props = {
  x: string,
}

const withReferral = <PassedProps: {}>(
    WrappedComponent: ComponentType<PassedProps>
): ComponentType<$Diff<PassedProps, Props>> => {
  class withReferral extends Component<PassedProps> {
    render() {
      return (<WrappedComponent {...this.props} x={'test'} />);
    }
  }

  return withReferral;
};

export default withReferral;
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:"无法返回withReferral,因为withReferral [1]的静态中缺少可调用签名,但存在于React.StatelessFunctionalComponent [2]中."

用[1]引用return withReferral和[2]引用React定义:React$StatelessFunctionalComponent<Props>

谁有任何帮助?

Dav*_*han 5

您错过x了WrappedComponents道具可能缺少的类型.如Flow HOC文档中所述,注入属性的类型需要与void例如联合x: string | void.

// @flow
import React, { Component } from 'react';
import type { ComponentType } from 'react';

type Props = {
  x: string | void,    // <<== HERE
}

const withReferral = <PassedProps: {}>(
    WrappedComponent: ComponentType<PassedProps>
): ComponentType<$Diff<PassedProps, Props>> => {
  class withReferral extends Component<PassedProps> {
    render() {
      return (<WrappedComponent {...this.props} x={'test'} />);
    }
  }

  return withReferral;
};

export default withReferral;
Run Code Online (Sandbox Code Playgroud)

(试试)