如何在FlowType中使用React $ Element?

时间:2017-04-22 08:35:55

标签: reactjs flowtype

这是我简单的<ListItem />反应组件。我希望它有一个标记道具,它只允许两种类型的组件,<Icon /><Label />

import React, { Element } from 'react';

import { Icon } from '../Icon';
import { Label } from '../Label';

type Props = {
  marker?: Element<Icon> | Element<Label>,
};

const ListItem = ({ marker }: Props) => {
  return (
    <div>{marker}</div>
  );
};

export default ListItem;

如何在FlowType中表示简单的用例?我尝试了以下但是所有这些似乎都不起作用。这就是为什么我想知道如何正确使用 React $ Element 来准确地允许两种特殊类型的反应组件?

type Marker = Icon | Label;

type Props = {
  marker?: Element<Marker>,
};
type Props = {
  marker?: Element<Icon> | Element<Label>,
};

1 个答案:

答案 0 :(得分:0)

您尝试的模式将在Flow版本0.53.0及更高版本中稍作更改:Element的类型参数是类型表达式位置,但是Icon和{{1}是价值观。您需要使用Label来引用其类型:

typeof

React的流式类型定义在v0.53.0中发生了重大变化,包括将type Props = { marker?: Element<typeof Icon> | Element<typeof Label>, }; 的类型参数从Element切换为Config的更改这使得讨论特定组件创建的元素变得更加容易。

Hack for Flow v0.52.0及更早版本

@Lewis Chung在评论中指出,Flow v0.53.0之前的React$ElementType参数Config是由表达式Element创建的。如果$Diff<Props, DefaultProps>Icon具有不同的道具类型,那么您可以使用类似这样的黑客来区分旧版Flow中这些组件创建的元素:

Label

假设type Props = { marker?: Element<IconProps> | Element<LabelProps>, }; Icon没有默认道具。如果他们这样做,那么你需要扩展类型以产生适当的差异:

Label