React.Component props中的不相交并集

问题描述 投票:1回答:1

我最近偶然发现了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);

不幸的是,我无法使该设置正常工作,我也不知道为什么。

我将方案隔离到这个小片段:https://flow.org/try/#0JYWwDg9gTgLgBAKjgQwM5wEoFNkGN4BmUEIcA5FDvmQNwBQdMAnmFnAPIBuWUyANnwAKxMOgC8cAN504cUMgDmWAKpQ+ALjioYUYADsFAGhlwArqh57kILJu26DxgL71GLNgElUgvsn3CIUTgJaVlgVABRABNgGGQAIz5bOAJ+C2NZUzA+CGQo1Q04PVMBZ1dmVjgvaNiEpICgkJNwmrjE5J1TLAyzbNz8tTsdfSM6FwYKtgbxDm5eAWm4ADI4AAovHz89RYAfKsiYtvqRVABKV1xfVHQAZRIsGAALEbgsAA8YLD0o9Gw8GAAdIJTJQAMIkSB6L4wAA80wAfFIxgxcBA9No5Adau1NPEIBA+ME4J0sK4YXcbE8Xs0QIoVGoxAAiBK4RkmcyWaxYJkcqBWGxssJYo7cyQtQ51LBOdl9PIFMRi4WSuAAfjgjKyOTlakZcE0xQE0oA9PCgA

外面有人可以向我解释为什么我遇到以下错误吗?

<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]

非常感谢!

reactjs flowtype
1个回答
0
投票

您会收到此错误,因为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}
/>

您还在为这个问题而苦苦挣扎吗?

© www.soinside.com 2019 - 2024. All rights reserved.