【发布时间】:2019-11-10 04:18:14
【问题描述】:
我正在导入一个 svg 文件以在我的项目中用作图像。 svg 文件中有一种颜色,我想将其更改为我自己的颜色(提前不知道)。我意识到 getSourceCode 和 setSourceCode 不是真正的方法,但我用它们来展示我想要完成的工作。
import React from "react";
import emptyOrderImage from "./images/illustrations/empty_order.svg";
function CurrentOrder(props) {
// Trying to get svg source code as string
let svgSourceCodeString = emptyOrderImage.getSourceCode();
// Assume the new color was dynamically loaded
const newColor = "#FAFAFA";
// I am trying to replace all occurences of #FFA500 with the new color
const newSourceCode = originalSourceCode.replace(/#FFA500/gi, newColor);
// Now I need to set svg to new source code
emptyOrderImage.setSourceCode(newSourceCode);
return (
<div style={{ flex: "display", justifyContent: "center" }}>
<img src={emptyOrderImage} style={{ width: 200, height: 200 }} />
</div>
);
}
export default CurrentOrder;
【问题讨论】:
-
使用
fill改变 svg 的颜色。 -
更容易将每个单独的标签编写为 react SFC,然后像通常使用 react IMO 一样动态渲染
-
@Kobe 有多个填写 svg 源,并不是所有我都想替换。我只想替换某些颜色(#FFA500)。
-
@DanielLizik 这有点棘手,因为我正在使用我在线下载的多个 svg 插图,因此如果我要为每个标签创建 SFC,则必须始终添加新插图需要一些努力。这就是为什么我认为简单地替换十六进制是最简单的解决方案(更少的维护)
-
@user3614030 github.com/smooth-code/svgr
标签: javascript reactjs svg create-react-app