【问题标题】:How do you render a different SVG onhover using react如何使用 React 渲染不同的 SVG onhover
【发布时间】:2019-08-13 03:05:27
【问题描述】:

我正在尝试渲染悬停时的 SVG 的不同颜色,但我想不出最好的方法。

当我查看这个问题时,它告诉我使用 fill:{color} 但我无法让它工作。我尝试创建两种不同的 SVG,一种是我通常想要的颜色(cancelBlack),另一种是我想要的悬停颜色(cancelBlue)。然后我尝试这样做:

.cancelBlack:hover{
    display:none;
}
.cancelBlue{
    display: none;
}
.cancelBlue:hover{
    display:flex;
}
//heres how im calling it in react
<button type="button" className='cancelBlack'>
    <ReactSVG src={Cancel} />
</button>
<button type="button" className='cancelBlue'>
    <ReactSVG src={CancelBlue} />
</button>

这是 SVG 的源代码:

    <?xml version="1.0" encoding="utf-8"?>
    <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
    <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"
        width="24px" height="24px" viewBox="0 0 24 24" enable-background="new 0 0 24 24" xml:space="preserve">
    <g>

            <polyline fill="none" stroke="#4D4D4D" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="
            17.686,6.303 12,11.986 17.712,17.697    "/>

            <polyline fill="none" stroke="#4D4D4D" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="
            6.316,6.303 12,11.986 6.289,17.697  "/>
    </g>
    </svg>

我不确定如何撤消显示,所以我只使用了 display:flex。感谢您的帮助。

【问题讨论】:

  • 能发下 ReactSVG 组件的源代码吗?您可能需要定位路径而不是填充,具体取决于构成 SVG 的元素。

标签: css reactjs svg


【解决方案1】:

您可以使用opacityfill-opacity 代替显示属性。

.cancelHover {
    position: absolute;
    z-index: 0;
}
.cancelNormal {
    opacity: 1;
    z-index: 1;
}
.cancelNormal:hover{
    opacity: 0;
}
...
<button type="button" className='cancelHover'>
    <ReactSVG src={CancelHover} />
</button>
<button type="button" className='cancelNormal'>
    <ReactSVG src={CancelNormal} />
</button>

另一种选择:

您需要删除 svg 文件中的 fillstroke attrs。

它们是内联样式,因此您无法在 css 样式中更改它。

根据您的 svg 文件,它使用笔触,因此您需要在 css 中更改笔触颜色。

.cancelNormal {
    stroke: #4D4D4D;
    z-index: 1;
}
.cancelNormal:hover{
    stroke: #0000;
    opacity: 0;
}

您还可以使用 stroke-width: 0 隐藏您的 svg 图片。

【讨论】:

  • 即使不透明度设置为 0,cancelNormal 似乎也不会在悬停时消失
  • @sayu 我根据你的 svg 文件更新了我的答案。
【解决方案2】:

您可能需要执行以下操作: 您的 CSS 以 SVG 本身而不是构成 SVG 的元素为目标。

.cancelBlue:hover { fill: #{color} }

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2021-09-11
    • 1970-01-01
    • 2021-06-04
    • 2021-08-04
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 2017-11-16
    相关资源
    最近更新 更多