React无状态功能组件的流返回类型是什么?



如果我有这样的内容

const RandomComponent = (props) => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent type={props.type} />
  </div>
)

我将如何用Flow注释返回类型,即,在下面的代码中应该用什么代替/* ??? */ ?

const RandomComponent = (props: { id: string, vino: number): /* ??? */ => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)

编辑:这就是Flow文档对无状态功能组件的描述。我可能是瞎了,但是我看不到任何关于返回类型的东西,只有prop类型

纯组件(与普通组件的render函数相同)的返回类型为?React$Element<any>

正如你可以在它的定义中读到的,React$Element有一个类型参数Config,它本身不是很有用,它只是为了与ReactClass的定义保持一致。

所以你的定义可以写成

const RandomComponent = (props: { id: string, vino: number }): React$Element<any> => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)

或者

import type { Element } from 'react'
const RandomComponent = (props: { id: string, vino: number }): Element<any> => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)

或者

import React from 'react'
const RandomComponent = (props: { id: string, vino: number }): React.Element<any> => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)

原来是React.Element,这是一个多态类型(我不是100%确定它的意思),所以正确的(足够的)代码将是

const RandomComponent = (props: { id: string, vino: number): React.Element<*> => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)

根据您的.flowconfig,将React$Element<any>设置为返回类型可能会抛出以下错误:

error Unexpected use of weak type "any" flowtype/no-weak-types

要避免这种情况,要么根本不传递类型:

type PropsType = { foo: string }
const Baz = (props: PropsType): React$Element =>
  <h1>Hello, { props.foo }</h1>

或者,传递props类型别名,而不是any:

type PropsType = { foo: string }
const Baz = (props: PropsType): React$Element<PropsType> =>
  <h1>Hello, { props.foo }</h1>

最新更新