反应-动态输出SVG组件

问题描述

我正在导入SVG文件作为ReactComponent。 然后,我想根据请求中的数据动态输出此组件。

import { ReactComponent as S1 } from '../../assets/images/characteristics/S1.svg';

 {characteristics.map(characteristic => (
   <div className="characteristic" key={characteristic.key}>
               <characteristic.key />
   </div>
}

其中的character.key保存了SVG的名称,在我的示例中为“ S1”

我不能输出该组件吗?

谢谢

解决方法

您可以尝试这样做:

import { ReactComponent as S1 } from "./path1.svg";
import { ReactComponent as S2 } from "./path2.svg";

// ...

function App() {
  // defining characteristics for demonstration purposes
  const characteristics = [
    { component: S1,key: "S1" },{ component: S2,key: "S2" }
  ];

  return (
    <div className="App">
      {characteristics.map(characteristic => (
        <div className="characteristic" key={characteristic.key}>
          <characteristic.component />
        </div>
      ))}
    </div>
  );
}

因此字符串"S1"对于密钥来说是一个很好的值,并且您从导入中使用S1来实际呈现svg组件。