React可以渲染什么类型的东西?

时间:2016-09-18 18:39:56

标签: flowtype

我有一个使用prop作为渲染组件的组件。由于React提供了很多创建组件类的方法,这个prop的类型注释应该是什么?

在下面的示例中,Wrap的正确类型注释是什么?

import React from 'react'

function Wrap ({ component: Component }) {
  return <Component foo />
}

class ClassComponent extends React.Component {
  render () {
    return <div>foo: {this.props.foo}</div>
  }
}
class ClassPureComponent extends React.PureComponent {
  render () {
    return <div>foo: {this.props.foo}</div>
  }
}

const CreateClassComponent = ReactClass.createClass({
  render () {
    return <div>foo: {this.props.foo}</div>
  }
})

function PureFunctionComponent ({ foo }) {
  return <div>foo: {foo}</div>
}

// These should all be valid
<Wrap component={ClassComponent} />
<Wrap component={ClassPureComponent} />
<Wrap component={CreateClassComponent} />
<Wrap component={PureFunctionComponent} />

2 个答案:

答案 0 :(得分:4)

使用ReactClass<any>是不安全的,因为它允许

<Wrap component={(props: {bar: string}) => <div>{props.bar}</div>} />;

键入安全替代

type FunctionComponent<P> = (props: P) => ?React$Element<any>;
type ClassComponentT<D, P, S> = Class<React$Component<D, P, S>>;
type Component<D, P, S> = ClassComponentT<D, P, S> | FunctionComponent<P>;

function Wrap ({ component: Component }: {component: Component<void, { foo: any }, void>}) {
  return <Component foo />
}

答案 1 :(得分:1)

我认为ReactClass<any>是您正在寻找的类型。

// @flow
import React from 'react'

function Wrap ({ component: Component }: {component: ReactClass<any>}) {
  return <Component foo />
}

class ClassComponent extends React.Component {
  render () {
    return <div>foo: {this.props.foo}</div>
  }
}

class ClassPureComponent extends React.PureComponent {
  render () {
    return <div>foo: {this.props.foo}</div>
  }
}

const CreateClassComponent = React.createClass({
  render () {
    return <div>foo: {this.props.foo}</div>
  }
});

function PureFunctionComponent ({ foo }) {
  return <div>foo: {foo}</div>
}

// These should all be valid

<Wrap component={ClassComponent} />;
<Wrap component={ClassPureComponent} />;
<Wrap component={CreateClassComponent} />;
<Wrap component={PureFunctionComponent} />;

Example on flowtype.org/try

有一个反应更高阶组件here in the docs

的例子