【问题标题】:Why this SVG image from sprite-sheet is not getting rendered in HTML but not in React?为什么这个来自 sprite-sheet 的 SVG 图像没有在 HTML 中呈现,但没有在 React 中呈现?
【发布时间】:2020-11-20 03:17:05
【问题描述】:

我有这个 SVG sprite 的代码

<symbol xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 22 22" id="github">
    <defs>
      <pattern id="a" preserveAspectRatio="none" width="100%" height="100%" viewBox="0 0 436 428">
        <image width="436" height="428" xlink:href="data:image/png;base64,.........."></image>
      </pattern>
    </defs>
    <circle cx="11" cy="11" r="11" fill="#fff"></circle>
    <path fill="url(#a)" d="M0 0h22v22H0z"></path>
</symbol>

GithHub 图标用 HTML 代码完美呈现,

<svg class="icon">
  <use xlink:href="#github"></use>
</svg>

当我使用 React.JS 时,图标没有显示出来。

icons2.svg

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <symbol xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 22 22" id="github">
        <defs>
          <pattern id="a" preserveAspectRatio="none" width="100%" height="100%" viewBox="0 0 436 428">
            <image width="436" height="428" xlink:href="data:image/png;base64,..."></image>
          </pattern>
        </defs>
        <circle cx="11" cy="11" r="11" fill="#fff"></circle>
        <path fill="url(#a)" d="M0 0h22v22H0z"></path>
      </symbol>
    </defs>
    </svg>

App.tsx

import icons from './icons2.svg';
let five = 'github';

class App extends Component {
 
    render() {
        return (
            <div>
               <svg>
                  <use href={`${icons}#${five}`} />
               </svg>
           </div>
        );
    }

我在这里做错了什么?

【问题讨论】:

  • 你能澄清一下吗?
  • 它没有用
  • 具有硬编码 id 值的组件是footgun。

标签: html reactjs svg webpack


【解决方案1】:

如果你使用 Create React App,你可以这样做:

import React from "react";
import { ReactComponent as ReactSprite } from "./icons.svg";
let five = "github";

export default function App() {
  return (
    <div className="App">
      <ReactSprite />
      <svg>
        <use href={`#${five}`} />
      </svg>
    </div>
  );
}

如果没有,您需要安装 SVGR 并将其用作 webpack 加载器。

【讨论】:

  • 有些图像是按照这种方法渲染的,有些不是。
  • 如果不确切知道相关 svg 中的内容,就很难知道可能是什么问题。
猜你喜欢
  • 2022-01-16
  • 2021-12-05
  • 2020-07-02
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多