reactjs - 如何使用组件创建联合类型?
问题描述
假设我有一个辅助函数,它返回带有一些常量的通用组件的包装器
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.
解决方案
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>
);
}
推荐阅读
- sql - 如何按另一个表中的外键值的数量对一个表进行排序?
- excel - 如何对范围内同一行的单元格应用 COUNTIFS 公式
- javascript - 仅在播放器暂停时显示元素
- c++ - 如何将我的 UWP 页面设置为在启动时具有恒定的宽度和高度?
- tor - 是否可以将 Mattermost 实例作为洋葱服务运行?
- c - 递归:如何保持 for 循环中不断变化的变量在递归期间不发生变化?
- vue.js - 尝试从 vuejs 组件调度动作时,vuex 未知动作类型
- html - 如何使用 css 为 html 字符添加边框颜色?
- sql-server - 用户会话卡在killed\rollback 状态
- unity3d - Unity:索引问题超出了数组的范围