这是我简单的<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>,
};
答案 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
的更改这使得讨论特定组件创建的元素变得更加容易。
React$ElementType
参数Config
是由表达式Element
创建的。如果$Diff<Props, DefaultProps>
和Icon
具有不同的道具类型,那么您可以使用类似这样的黑客来区分旧版Flow中这些组件创建的元素:
Label
假设type Props = {
marker?: Element<IconProps> | Element<LabelProps>,
};
和Icon
没有默认道具。如果他们这样做,那么你需要扩展类型以产生适当的差异:
Label