我有一个 SVG 用作 <img>
标签。使用样式化组件我试图达到在悬停时更改笔触颜色的程度。
我导入了SVG:
import BurgerOpenSvg from '../../images/burger_open.svg';
我为它创建了一个样式组件:
const BurgerImageStyle = styled.img`
&:hover {
.st0 {
stroke: red;
}
}
`;
我使用它:
<BurgerImageStyle alt="my-burger" src={BurgerOpenSvg}/>
结果是,我的 SVG 显示正确,但是 无颜色变化悬停时。
我使用的 SVG 来源:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 38 28.4" style="enable-background:new 0 0 38 28.4;" xml:space="preserve">
<style type="text/css">
.st0{fill:none;stroke:#221f1f;stroke-width:2;stroke-miterlimit:10;}
</style>
<g>
<g id="XMLID_7_">
<line class="st0" x1="0" y1="1" x2="38" y2="1"/>
</g>
<g id="XMLID_6_">
<line class="st0" x1="0" y1="14.2" x2="38" y2="14.2"/>
</g>
<g id="XMLID_5_">
<line class="st0" x1="0" y1="27.4" x2="38" y2="27.4"/>
</g>
</g>
</svg>
SVG 渲染如下:
甚至可以更新
<img>
中加载的 SVG 上的类吗?标签?或者必须是内联的 <svg>
标签?
最佳答案
所以我研究了这个。事实证明,您无法使用 <img>
为正在加载的 SVG 图像设置 CSS 样式。标签。
我所做的是这样的:
我像这样内联了我的 SVG:
<BurgerImageStyle x="0px" y="0px" viewBox="0 0 38 28.4">
<line x1="0" y1="1" x2="38" y2="1"/>
<line x1="0" y1="14.2" x2="38" y2="14.2"/>
<line x1="0" y1="27.4" x2="38" y2="27.4"/>
</BurgerImageStyle>
然后我使用样式化组件来样式化
BurgerImageStyle
:const BurgerImageStyle = styled.svg`
line {
stroke: black;
}
&:hover {
line {
stroke: purple;
}
}
`;
这奏效了。
关于reactjs - 使用样式化组件更改 SVG 笔触的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56692784/