首页 > 解决方案 > 如何使用组件创建联合类型?

问题描述

假设我有一个辅助函数,它返回带有一些常量的通用组件的包装器

function fooBar(ComponentVariant: ComponentVariantType) {
  return (
    <Foo>
     <ComponentVariant>
       <Bar />
     </ComponentVariant>
    </Foo>
  );
}

ComponentVariantType类似的东西在哪里type ComponentVariantType = FunctionalComponentA | FunctionalComponentB | FunctionalComponentC

现在我收到一个构建错误说:

FunctionalComponentA refers to a value, but is being used as a type here.
FunctionalComponentB refers to a value, but is being used as a type here.
FunctionalComponentC refers to a value, but is being used as a type here.

标签: reactjstypescriptgenerics

解决方案


FunctionalComponentA是在运行时表示函数的值。要获取此类值的类型,您需要使用typeof类型运算符:

type ComponentVariantType = typeof FunctionalComponentA | typeof FunctionalComponentB | typeof FunctionalComponentC.

尽管取决于这些组件的定义方式,ComponentVariant但传入的道具何时需要与所有组件兼容。

declare const FunctionalComponentA: React.FC<{ a: string }>
declare const FunctionalComponentB: React.FC<{ b: string }>
declare const FunctionalComponentC: React.FC<{ c: string }>

type ComponentVariantType = typeof FunctionalComponentA | typeof FunctionalComponentB | typeof FunctionalComponentC

function fooBar(ComponentVariant: ComponentVariantType) {
  return (
    <div>
    <ComponentVariant a="" b="" c=""></ComponentVariant> /* Must have all props*/
    </div>
  );
}

推荐阅读