从Typescript对象获取JSX元素



我的typescript objectstate.ts如下

import { IconCalendarEvent, TablerIcon, IconRun } from "@tabler/icons";
export const StateIcon  = {    
Validated: IconCalendarEvent,
Running: IconRun
};

基本上,这推断为

const StateIcon: {
Validated: TablerIcon;
Running: TablerIcon;
}

现在在我的React Component中,我想基于状态返回JSX Element

所以我写了一个函数

const getIcon = (state: string) => {
const r = (_.keys(StateIcon) as (keyof typeof StateIcon)[]).find((k) => {
return k === state;
});
return <StateIcon[r] /> 

};

但这不适用于JSX element type 'StateIcon' does not have any construct or call signatures

如果我尝试下面的硬编码,它工作得很好。

return <StateIcon.Running /> 

我尝试将签名更改为

const getIcon = (state: string) => {
const Icon = StateIcon[state];
return <Icon />;
};

元素隐式具有"any"类型,因为类型的表达式"string"不能用于索引类型"{Validated:TablerIcon;正在运行:TablerIcon;}'。没有带类型参数的索引签名在类型"{Validated:TablerIcon;正在运行:"上找到"string"TablerIcon;}'

我在这里缺少什么

您可以有一个"动态的";组件:

const getIcon = (state: string) => {
const r = (_.keys(StateIcon) as (keyof typeof StateIcon)[]).find((k) => {
return k === state;
});
// Store the chosen component in a variable starting with Uppercase
const DynamicIcon = StateIcon[r];
return <DynamicIcon /> 
};

相关内容

  • 没有找到相关文章

最新更新