将组件作为道具传递时在 Flow 中键入 React 组件
Posted
技术标签:
【中文标题】将组件作为道具传递时在 Flow 中键入 React 组件【英文标题】:Typing React components in Flow when passing a component as a prop 【发布时间】:2017-09-20 19:40:38 【问题描述】:我想将一个 React 组件作为输入道具传递给另一个 React 组件。我试图将它引用为 React.Component 但是当我在渲染方法中使用传递的组件时出现错误。这就是我编写流程代码的方式。
/* @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)
我应该如何正确键入输入组件?
【问题讨论】:
【参考方案1】:在 Flow 0.93.0 版本上,您可以执行以下操作。
从'react'导入类型元素作为ReactElement; 类型道具 = 组件:反应元素【讨论】:
【参考方案2】:从 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。如cmets中所述,有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>;
【讨论】:
该示例似乎不再起作用,我在文档中找不到任何关于ReactClass
的信息。这个问题是否可能适用于旧版本的流程?
确实,ReactClass 似乎已被删除:github.com/facebook/flow/commit/…
现在看起来类型是 React.ComponentType以上是关于将组件作为道具传递时在 Flow 中键入 React 组件的主要内容,如果未能解决你的问题,请参考以下文章
使用 Material UI makeStyles 时键入的道具