# React技巧之改变SVG的颜色
原文链接:https://bobbyhadz.com/blog/react-change-color-of-svg (opens new window)
作者:Borislav Hadzhiev (opens new window)
正文从这开始~
# 总览
在React中,改变SVG的颜色:
- 不要在SVG上设置
fill和stroke属性。 - 将SVG作为组件导入。
- 在组件上设置
fill和stroke属性,比如说,<MyLogo fill="black" stroke="yellow" />。
import {ReactComponent as MyLogo} from './my-logo.svg';
export default function App() {
return (
<div>
<MyLogo fill="black" stroke="yellow" />
</div>
);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
这里是示例中svg的代码。
<svg width="400" height="400">
<circle cx="100" cy="100" r="50" stroke-width="5" />
</svg>
1
2
3
2
3
需要注意的是,我们没有在svg元素上设置fill和stroke属性。这两个属性如果没有在svg中定义,那么只有在通过设置组件属性时才会应用。
fill属性用来设置对象内部的颜色,stroke属性用来设置对象周围线条的颜色。
另外,你可以把你的SVG粘贴到一个组件中,并把颜色作为属性传递。
function MyLogo({fill, stroke}) {
// 👇️ paste SVG into a component
// take fill and stroke colors as props
return (
<svg fill={fill} stroke={stroke} width="400" height="400">
<circle cx="100" cy="100" r="50" stroke-width="5" />
</svg>
);
}
export default function App() {
return (
<div>
<MyLogo fill="black" stroke="yellow" />
</div>
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
上面的代码达到了同样的效果,但我们直接将SVG存储在一个组件中,而不是从一个扩展名为svg的文件中导入。
需要注意的是,MyLogo组件接收fill和stroke的值作为属性,并将它们应用到svg元素中。
如果你没有一个允许你将SVG导入组件的loader,这应该是你的首选方法。