Using Styled Components to change the color of an SVG's stroke

若如初见. 提交于 2020-06-13 05:30:19

问题


I have an SVG I'm using as an <img> tag. Using Styled Components I am trying to get to a point where I change the stroke color upon hover.

I imported the SVG:

import BurgerOpenSvg from '../../images/burger_open.svg';

I Created a Styled Components for it:

   const BurgerImageStyle = styled.img`
    &:hover {     
        .st0 {
          stroke: red;
        }
    }
`;

And I use it:

<BurgerImageStyle alt="my-burger" src={BurgerOpenSvg}/>     

The result is, my SVG is displayed correctly, but no color change upon hovering.

Source for the SVG I use:

<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>

The SVG Renders as follows:

Is it even possible to update the class on an SVG loaded in an <img> tag? or must it be inline <svg> tag?


回答1:


So I looked into this. Turns out you cannot CSS style an SVG image you're loading using the <img> tag.

What I've done is this:

I inlined my SVG like this:

 <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>

Then I used Styled Components to style BurgerImageStyle:

const BurgerImageStyle = styled.svg`
    line {
      stroke: black;
    }    
    &:hover {
      line {
        stroke: purple;
      }
    }     
`;

This worked.



来源:https://stackoverflow.com/questions/56692784/using-styled-components-to-change-the-color-of-an-svgs-stroke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!