javascript - 从另一个文件夹导入 SVG 图标
问题描述
我想从我的图标文件夹中导入 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 加载器,并将加载资产的源映射到字段ReactComponent。你需要做的是:
const { ReactComponent: Icon } = require(`./icons/${name}.svg`);
return (
<Icon />
);
推荐阅读
- symfony - Symfony Sonata 管理面板按出现次数排序(doctrin query builder)
- flutter - 带有 statefull 小部件的 Flutter listview builder 不会使用父小部件中的设置状态进行更新
- python - Dash 应用程序在选项卡之间切换时防止自动刷新
- c - 如何用C设计一个简单的登录系统?
- javascript - 如何使用 Vuetify 在图标和文本字段之间创建空间
- java - 如何将以下 java 查询放入 switch case?
- typescript - 如何使 tslint 接受以“_”开头的变量名
- swift - Swift didSet for var 使用 @Binding 在子级中更改
- c++ - 未找到 SDL_Mixer dll
- angular - Elasticsearch 部分搜索词 | 角