如何从自定义React组件继承而不丢失流类型信息?

时间:2017-01-06 21:55:23

标签: reactjs flowtype

我有一个继承自React.Component的BaseComponent。应用程序中的所有其他组件都继承自BaseComponent。我需要输入BaseComponent,以便继承自它的其他组件被Flow作为React组件处理。这就是我目前所拥有的:

class BaseComponent<P, S> extends React.Component<$Shape<P>, P, S> {
  ...
}

class OtherComponent extends BaseComponent {
  props: {};
  state: {}:
  ...
}

这里是working example。 Flow正确检查OtherComponent中的道具,状态等。

然而,在BaseComponent中,我得到了一些模糊的错误:

  1. S: This type is incompatible with 'undefined. Did you forget to declare S?

  2. P: This type is incompatible with 'undefined. Did you forget to declare P?

  3. Did you forget to declare some incompatible instantiation ofŠ?: This type is incompatible with 'some incompatible instantiation ofŠ'

  4. 我正在努力理解错误信息。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

这对我有用:

class BaseComponent<D, P, S> extends React.Component<D, P, S> {
    static defaultProps: D
    props: P
    state: S
    yourCustomFunction(): void
}

class You extends BaseComponent<any, any, any> {
  --- component body ---
}

答案 1 :(得分:0)

经过大量的实验,这就是我最终的结果。它似乎工作正常:

class BaseComponent<Props:Object, State, DefaultProps: $Shape<Props>> extends React.Component<DefaultProps, Props, State> {
  static defaultProps: $Abstract<DefaultProps>;
  props: Props;
  state: $Abstract<State>;
}

除了将类型参数传递给baseComponent之外,关键是在React.Components上定义props / state /和defaultProps。我不确定为什么这是必要的,但它确实解决了这个问题。

答案 2 :(得分:0)

为了使我的代码能够使用可变数量的通用参数,这就是我最终键入组件的方式:

export default class NewComponent<P, S = {}> extends Component<P, S> {
  props: P
  state: S
  ...
}