我最近偶然发现了flow-js(disjoint unions
)的https://flow.org/en/docs/types/unions/#disjoint-unions-,并试图在我的React.Component
道具中使用它们。
[基本想法是,我总是需要设置一组道具,并且根据属性,其他一些字段也需要具有内容。
在我的示例中,我希望有一个isEditable
标志-如果为true,则还需要设置字段uploadUrl
。如果isEditable
为假,则uploadUrl
必须为null。
// Base properties
type OverallProps = { imageUrl: string, username: string };
// Disjoint unions
type IsPlainProps = { isEditable: false, uploadUrl: null };
type IsEditableProps = { isEditable: true, uploadUrl: string };
// My Props
type Props = OverallProps & (IsPlainProps | IsEditableProps);
不幸的是,我无法使该设置正常工作,我也不知道为什么。
外面有人可以向我解释为什么我遇到以下错误吗?
<Something
^ Cannot create `Something` element because: Either boolean [1] is incompatible with boolean literal `false` [2] in property `isEditable`. Or boolean [1] is incompatible with boolean literal `true` [3] in property `isEditable`.
References:
23: const isEditable: bool = true;
^ [1]
9: isEditable: false,
^ [2]
14: isEditable: true,
^ [3]
非常感谢!
您会收到此错误,因为true和false是值。
并且您正在定义数据类型,例如这样做:
import * as React from 'react';
type OverallProps = {
imageUrl: string,
username: string,
};
type IsPlainProps = {
isEditable: bool,
uploadUrl: ?string,
};
type IsEditableProps = {
isEditable: bool,
uploadUrl: string,
};
type Props = OverallProps & (IsPlainProps | IsEditableProps);
class Something extends React.PureComponent<Props> {
}
const isEditable: bool = true;
<Something
imageUrl="abc"
username="username"
isEditable={isEditable}
uploadUrl={isEditable ? "uploadUrl" : null}
/>
您还在为这个问题而苦苦挣扎吗?