简体   繁体   English

从另一个文件夹导入 SVG 图标

[英]Import SVG icons from another folder

I want to import svg icons from my icon folder, to change the color of the icons I have to give fill parameter to path inside SVG.我想从我的图标文件夹中导入 svg 图标,以更改图标的颜色,我必须将填充参数提供给 SVG 内的路径。 So i need import and to show only SVG but not like <img src="icon.svg"/> .所以我需要导入并只显示 SVG 但不像<img src="icon.svg"/>

I first put one SVG right inside the component and it shows no problem.我首先将一个 SVG 放在组件内部,它显示没有问题。 but I have a lot of icons I can't put everything inside the component.但是我有很多图标我不能把所有的东西都放在组件里。

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>
  );
};

when i am writing as {require("./icons/${name}.svg")} .当我写为{require("./icons/${name}.svg")}时。 this is showing me only path to SVG.这向我展示了通往 SVG 的唯一路径。 But i want import every SVG by name and only SVG但我想按名称导入每个 SVG 并且只导入 SVG

Ok, my friend.好的,我的朋友。

I guess you are using create-react-app and you don't need to configure your webpack (I hope nowadays no one knows what is webpack)我猜你正在使用create-react-app并且你不需要配置你的 webpack (我希望现在没有人知道什么是 webpack)

So, what did they in create-react-app is added loader for svg for you, and map source of the loaded asset to the field ReactComponent .那么,他们在create-react-app中为您添加了 svg 的加载器,并将加载资产的 map 源添加到字段ReactComponent What you need to do is:你需要做的是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM