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

问题描述 投票:2回答:3

我有一个继承自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 ofS?: This type is incompatible with 'some incompatible instantiation ofS'

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

reactjs flowtype
3个回答
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 ---
}

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上定义props / state /和defaultProps,除了将类型参数传递给React.Components。我不确定为什么这是必要的,但它确实解决了这个问题。


0
投票

为了让我的代码使用可变数量的泛型参数,这就是我最终输入组件的方式:

export default class NewComponent<P, S = {}> extends Component<P, S> {
  props: P
  state: S
  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.