我正在尝试提示如何向传递的组件添加某种 Prop 的HOC,如下所示:

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

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

[1]引用return withReferral,[2]引用React定义:React$StatelessFunctionalComponent<Props>
任何有帮助的人吗?

最佳答案

您丢失了WrappedComponents Prop 中可能需要丢失的x类型的信息。如Flow HOC docs中所述,注入(inject)属性的类型需要与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;

(Try)

关于javascript - 流类型:基于Typehinting类的HOC组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49007839/

10-11 13:34