Javascript 在Next.js中动态获取SVG图标

Javascript 在Next.js中动态获取SVG图标,javascript,reactjs,svg,next.js,Javascript,Reactjs,Svg,Next.js,我想动态获取SVG图标。我找到了这样做的方法,但似乎我犯了一些错误。我哪里做错了 Icon.js import React from "react"; import { ReactComponent as Bollards } from "./icons/bollards.svg"; import { ReactComponent as Earthquake } from "./icons/earthquake.svg"; import

我想动态获取SVG图标。我找到了这样做的方法,但似乎我犯了一些错误。我哪里做错了

Icon.js

import React from "react";
import { ReactComponent as Bollards } from "./icons/bollards.svg";
import { ReactComponent as Earthquake } from "./icons/earthquake.svg";
import { ReactComponent as Fire } from "./icons/fire.svg";
import { ReactComponent as Healthy } from "./icons/heartbeat.svg";
import { ReactComponent as Home } from "./icons/home.svg";
import { ReactComponent as Planting } from "./icons/planting.svg";
import { ReactComponent as Business } from "./icons/suitcase.svg";
import { ReactComponent as Travel } from "./icons/airplane-around-earth.svg";

const iconTypes = {
  bollards: Bollards,
  earthQuake: Earthquake,
  fire: Fire,
  healthy: Healthy,
  home: Home,
  planting: Planting,
  business: Business,
  travel: Travel
};

const IconComponent = ({ name, ...props }) => {
  let Icon = iconTypes[name];
  return <Icon {...props} />;
};

export default IconComponent;
import React from "react";
import Icon from "./icon";

export default function Features() {
  return (
    <div>
      <Icon name="bollards" />
    </div>
  );
}
您可以使用它将SVG作为组件导入到您的React应用程序中

您需要添加
@svgr/webpack
作为依赖项,并像这样修改
next.config.js
文件

next.config.js

module.exports={
网页包(配置){
config.module.rules.push({
测试:/\.svg$/,,
使用:[“@svgr/webpack”]
});
返回配置;
}
};
然后,无需使用
ReactComponent
即可导入图标

Icon.js

从“React”导入React;
从“./icons/Bollards.svg”导入护柱;
从“./icons/sevent.svg”导入地震;
从“./icons/Fire.svg”导入火;
从“/icons/heartbeat.svg”导入健康状态;
从“./icons/Home.svg”导入主页;
从“./icons/planning.svg”导入种植;
从“./icons/castle.svg”导入业务;
从“/icons/planet around earth.svg”导入旅行;
常量图标={
护柱:护柱,
地震:地震,
火:火,
健康:健康,,
家:家,
种植:种植,,
业务:业务,,
旅行:旅行
};
常量IconComponent=({name,…props})=>{
让Icon=iconTypes[name];
返回;
};
导出默认IconComponent;

演示正在运行。

它运行正常。非常感谢您抽出宝贵的时间和帮助。很高兴它奏效了。如果它解决了你的问题,你也可以投票和/或:)谢谢
error - ./components/icon.js
Attempted import error: 'ReactComponent' is not exported from './icons/bollards.svg' (imported as 'Bollards').