【问题标题】:React, React-svg. How to restore original colors反应,反应-svg。如何恢复原来的颜色
【发布时间】:2021-07-09 11:43:52
【问题描述】:

我有一组.svg 图标对于不同的路径有不同的颜色。目前我正在使用react-svg 包来渲染它们,它看起来像这样:

<span>
    <ReactSVG
       src="/icons/setting.svg"
       beforeInjection={svg => {
         svg.classList.add("svg-classname");
       }}
    />
</span>

这很好用。现在我想将所有路径颜色更改为灰色并通过用户悬停恢复所有原始颜色,我试图在我的scss 中通过以下方式实现:

.svg-classname {
      path,
      rect,
      circle {
        fill: #888;
        color: #888;
      }
      &:hover {
        path,
        rect,
        circle {
          fill: initial;
          color: initial;
        }
      }
}

这显然行不通!我不是 svgs 专家,所以任何建议(即使不使用 react-svg)都非常受欢迎。

【问题讨论】:

  • 两个建议:尝试“继承”而不是“初始”,添加“描边”和“填充”。希望对您有所帮助...

标签: css reactjs svg


【解决方案1】:

针对您的问题的简单 D3 解决方法:

d3.selectAll('.my-svg-icon path')
  .each(function() {
    const path = d3.select(this);
    const originalColor = path.attr('fill');
    path.attr('fill', 'gray')
      .on('mouseenter', () => path.attr('fill', originalColor))
      .on('mouseleave', () => path.attr('fill', 'gray'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg class="my-svg-icon">
  <path d="M 10,10 H 50 V 50 H 10 Z" fill="red"/>
</svg>
<svg class="my-svg-icon">
  <path d="M 10,10 H 50 V 50 H 10 Z" fill="blue"/>
</svg>

【讨论】:

  • 这太棒了!感谢回复
猜你喜欢
  • 2021-02-27
  • 2016-08-30
  • 2020-11-21
  • 1970-01-01
  • 2019-04-20
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多