【发布时间】:2021-12-07 19:30:54
【问题描述】:
我正在使用带有 TypeScript 的 React,并且在一个目录中有 5 个 SVG 图标,我可以像这样导入
import * as OtherIconsGroup from '../src/other-icons';
然后我可以像引用每个图标
<OtherIconsGroup.Loading fill={fillColor} width={size} height={size} />
<OtherIconsGroup.Like fill={fillColor} width={size} height={size} />
<OtherIconsGroup.Copy fill={fillColor} width={size} height={size} />
etc...
现在的问题是我需要向这个目录添加 30 多个图标,我正在寻找一种方法来动态渲染所有组件,基本上类似于
{Object.keys(OtherIconsGroup).map(icon => {
return(
<OtherIconsGroup.{icon} fill={fillColor} width={size} height={size} />
)
}
这显然不起作用,所以我试图了解如何定义一个组件,给它一个自定义名称并返回它。
{Object.keys(OtherIconsGroup).map(icon => {
const IconComponent = `OtherIconsGroup.${icon}`;
return(
<IconComponent fill={fillColor} width={size} height={size}/>
)
}
我在添加上面的 props 时遇到以下错误,因此寻求帮助以在 TypeScript 中正确定义组件,以便我可以添加 SVG 元素属性。
Type '{ fill: string; width: number; height: number; }' is not assignable to type 'IntrinsicAttributes'.
Property 'fill' does not exist on type 'IntrinsicAttributes'.ts(2322)
【问题讨论】:
标签: javascript reactjs typescript