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

İbr*_*him 4 javascript svg reactjs next.js

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

图标.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;
Run Code Online (Sandbox Code Playgroud)

特征.js

import React from "react";
import Icon from "./icon";

export default function Features() {
  return (
    <div>
      <Icon name="bollards" />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

尝试导出图标时出现此错误。

error - ./components/icon.js
Attempted import error: 'ReactComponent' is not exported from './icons/bollards.svg' (imported as 'Bollards').
Run Code Online (Sandbox Code Playgroud)

Zso*_*ros 9

您可以使用SVGR,它允许我们将 SVG 作为组件导入到您的 React 应用程序中。

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

next.config.js:

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: ["@svgr/webpack"]
    });
    return config;
  }
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以简单地导入图标,而无需使用ReactComponent.

Icon.js:

import React from "react";

import Bollards from './icons/bollards.svg';
import Earthquake from './icons/earthquake.svg';
import Fire from './icons/fire.svg';
import Healthy from './icons/heartbeat.svg';
import Home from './icons/home.svg';
import Planting from './icons/planting.svg';
import Business from './icons/suitcase.svg';
import 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;
Run Code Online (Sandbox Code Playgroud)

CodeSandbox 上提供了工作演示。