问题
I have this code for 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>
The GithHub icon is perfectly rendered with HTML code,
<svg class="icon">
<use xlink:href="#github"></use>
</svg>
When I use React.JS the icon is not getting displayed.
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>
);
}
What am I doing wrong here?
回答1:
If you are using Create React App you can do this:
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>
);
}
If not, you would need to install SVGR and use it as a webpack loader.
来源:https://stackoverflow.com/questions/63172121/why-this-svg-image-from-sprite-sheet-is-not-getting-rendered-in-html-but-not-in