Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - 使用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?(问题是:有办法吗?)

  ask by Rigil Kent translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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种不同的确切对象类型并将组件prop标记为其中之一:)
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(尝试)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...