如何在 Flow 中将道具类型定义为 <div>?

How do I define a prop type as a <div> in Flow?

我正在使用 ES6 类 编写 React 组件,我的 props 之一可以是 string<div>

如何告诉 Flow <div> 是可以接受的?

目前:

import React from 'react'

type Props = {
  title: string,
  content: string | // <- or a div
};

export class ThisComponent extends React.Component {
// ...

你应该使用 React.PropTypes.node:

Anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.

然后就在您的组件中使用它:

render() {
  return (
    <div className="myComponent">
      <h3>My super component</h3>
      <div className="content">
        {this.props.content}
      </div>
    </div>
  );
}

所以在你的组件声明之后:

ThisComponent.propTypes = {
  content: React.PropTypes.node,
  title: React.PropTypes.string,
};

你可以使用全局类型React$Element

type Props = {
  title: string,
  content: string | React$Element<any>
};

据我所知你不能只限制 divs 虽然

<ThisComponent title="mytitle" content={<div/>} /> // <= ok
<ThisComponent title="mytitle" content={<a/>} />   // <= ok as well

对于未来的旅行者,我认为 <div> 的流程类型是 HTMLDivElement

例如,在你上面的例子中,你想要一个字符串或 div:

type Props = { content: string | HTMLDivElement, };