简体   繁体   English

使用 Flow 的互斥属性

[英]Mutually exclusive attributes using Flow

I'm building a UI component in the company I work for.我正在我工作的公司中构建一个 UI 组件。 It's in React Native and it uses Flow to typecheck.它在 React Native 中并使用 Flow 进行类型检查。 Thing is I want the components to have certain variants but they force me to have nothing but booleans for components attributes.事情是我希望组件具有某些变体,但它们迫使我只有组件属性的booleans And I'd like the components to disallow the use of more than one variant.我希望组件不允许使用多个变体。

Let's say my component <Button> has two variants: primary and secondary .假设我的组件<Button>有两个变体: primarysecondary If I could use an attribute variant it would be easier because I would be able to use variant='primary' .如果我可以使用属性variant ,那就更容易了,因为我可以使用variant='primary' But I can't do that.但我不能那样做。 It has to be primary=true but I have to make it exclusive: if I have primary:true you shouldn't be allowed to use secondary:true in the same component.它必须是primary=true但我必须让它独占:如果我有primary:true你不应该被允许在同一个组件中使用secondary:true

I'been checking the docs but I couldn't find a way.我一直在检查文档,但找不到方法。 And it makes sense, why would you have one?这是有道理的,你为什么要拥有一个? Just stop using boolean 's for everything, right?只是停止使用boolean的一切,对吧?

Question is: Is there a way?问题是:有办法吗?

Not sure I follow all the magic you're trying to implement, but this one:不确定我是否遵循了您尝试实施的所有魔法,但是这个:

if I have primary:true you shouldn't be allowed to use secondary:true in the same component.如果我有primary:true你不应该被允许在同一个组件中使用secondary:true

Is quite easy to achieve with exact object types .使用 精确的对象类型很容易实现。 Just create 2 different exact object types and mark component props as one of those:只需创建 2 种不同的确切对象类型并将组件道具标记为其中之一:

type TPrimary = {|
  primary: boolean,
|};

type TSecondary = {|
  secondary: boolean,
|};

type T = TPrimary | TSecondary;

const C = (props: T) => <div {...props} />

const mounted = <C primary  />;

const mounted2 = <C secondary  />;

// error
const mounted3 = <C primary secondary  />

Try 尝试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM