在将组件作为prop传递时,在Flow中键入React组件

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

我想将一个React组件作为输入prop传递给另一个React组件。我试图将它引用为React.Component <*,*,*>但是当我在render方法中使用传递的组件时,我得到一个错误。这就是我写出流程代码的方式。

/* @flow */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

const Input = props => <div>Yo</div>

type DefaultProps = {
  InputComponent: Input
};

type Props = {
  InputComponent: React.Component<*, *, *>
};

class App extends Component<DefaultProps, Props, void> {
  static defaultProps = {
    InputComponent: Input
  };

  props: Props;

  render() {
    const { InputComponent } = this.props

    return (
      <div>
        <InputComponent />
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)

但是在App渲染方法中我得到了错误

React element `InputComponent` (Expected React component instead of React$Component)

我该如何正确输入输入组件?

reactjs flowtype
2个回答
12
投票

从v0.59.0开始,你应该使用React.Component。例如:

/* @flow */

import React from 'react';

const Input = props => <div>Yo</div>

type Props = {
  InputComponent: React.Component<*, *>
};

class App extends React.Component<Props, void> {
  static defaultProps = {
    InputComponent: Input
  };

  render() {
    const { InputComponent } = this.props

    return (
      <div>
        <InputComponent />
      </div>
    )
  }
}

Here is a working example为0.59.0。正如评论中提到的,有a description of the changes here

::在v0.59.0之前::

你应该使用ReactClass<*>而不是React.Component

这是一个working example,文档是here

/**
 * Type of a React class (not to be confused with the type of instances of a
 * React class, which is the React class itself). A React class is any subclass
 * of React$Component. We make the type of a React class parametric over Config,
 * which is derived from some of the type parameters (DefaultProps, Props) of
 * React$Component, abstracting away others (State); whereas a React$Component
 * type is useful for checking the definition of a React class, a ReactClass
 * type (and the corresponding React$Element type, see below) is useful for
 * checking the uses of a React class. The required constraints are set up using
 * a "helper" type alias, that takes an additional type parameter C representing
 * the React class, which is then abstracted with an existential type (*). The *
 * can be thought of as an "auto" instruction to the typechecker, telling it to
 * fill in the type from context.
 */
type ReactClass<Config> = _ReactClass<*, *, Config, *>;
type _ReactClass<DefaultProps, Props, Config: $Diff<Props, DefaultProps>, C: React$Component<DefaultProps, Props, any>> = Class<C>;

0
投票

在版本Flow 0.93.0上,您可以执行以下操作。


    import type { Element as ReactElement } from 'react';

    type Props = {
      component: ReactElement
    }

© www.soinside.com 2019 - 2024. All rights reserved.