簡體   English   中英

從另一個文件夾導入 SVG 圖標

[英]Import SVG icons from another folder

我想從我的圖標文件夾中導入 svg 圖標,以更改圖標的顏色,我必須將填充參數提供給 SVG 內的路徑。 所以我需要導入並只顯示 SVG 但不像<img src="icon.svg"/>

我首先將一個 SVG 放在組件內部,它顯示沒有問題。 但是我有很多圖標我不能把所有的東西都放在組件里。

import React from "react";
import { makeStyles } from "@material-ui/core/styles";

export const Gunicon = ({ name, height, width, color, bold }) => {
  const classes = makeStyles(theme => {
    /* i want to give style like this */
    return {
      gunicon: {
        "& svg": {
          height,
          width,
          "& path": {
            fill: color,
            stroke: color,
            strokeWidth: bold
          }
        }
      }
    };
  });

  /* this is working. but i dont like this */
  const ico = (
    <svg height={height} width={width} viewBox="0 0 512 512">
      <path d="test svg" fill={color} stroke={color} strokeWidth={bold} />
    </svg>
  );

  return (
    <div className={classes.gunicon}>
      {/* dont working */}
      {require(`./icons/${name}.svg`)}
      {/* working */}
      {ico}
    </div>
  );
};

當我寫為{require("./icons/${name}.svg")}時。 這向我展示了通往 SVG 的唯一路徑。 但我想按名稱導入每個 SVG 並且只導入 SVG

好的,我的朋友。

我猜你正在使用create-react-app並且你不需要配置你的 webpack (我希望現在沒有人知道什么是 webpack)

那么,他們在create-react-app中為您添加了 svg 的加載器,並將加載資產的 map 源添加到字段ReactComponent 你需要做的是:

  const { ReactComponent: Icon } = require(`./icons/${name}.svg`);
  return (
    <Icon />
  );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM