【问题标题】:Render multiple SVG icons dynamically动态渲染多个 SVG 图标
【发布时间】: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


    【解决方案1】:

    你们其实很亲近!只是 JSX 的小语法问题。

    可以这样做:

    const icons = Object.entries(OtherIconsGroup)
      .map(([_, Icon]) => <Icon fill={fillColor} width={size} height={size}/>);
    

    const icons = Object.map(OtherIconsGroup)
      .map((iconName) => {
        const Icon = OtherIconsGroup[iconName];
        return <Icon fill={fillColor} width={size} height={size}/>;
      });
    

    【讨论】:

    • 太棒了,谢谢。第一个建议非常适合我。
    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2013-07-05
    • 2021-03-22
    • 2019-09-21
    • 2018-08-28
    相关资源
    最近更新 更多