React and SVG sprite

北战南征 提交于 2020-01-14 12:51:26

问题


I am using React, and I am trying to load a svg icon from a sprite. My sprite is like this:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <symbol viewBox="0 0 28.3 28.3" id="square">
      <path d="M.3 30.7h27L13.8 3.8zM126.3-51.7c-8.8 0-16 7.2-16 16s7.2 16 16 16 16-7.2 16-16-7.2-16-16-16z" />
      <path d="M0 28.3h28.3L14.2 0 0 28.3zm5.3-3.2l8.9-17.7L23 25.1H5.3z" />
    </symbol>
    <symbol viewBox="0 0 28.3 28.3" id="circle">
      <circle cx="14.2" cy="14.2" r="14.2" />
    </symbol>
  </defs>
</svg>

And I load it with:

<svg viewBox="0 0 28.3 28.3" className="App-icon">
    <use xlinkHref="./sprite#square" />
</svg>

With no results. I made a sandbox as an example: https://codesandbox.io/s/l711v6j7v7


回答1:


If you want to reference it as external resource you need to use the proper URL to the svg file and it needs to be publicly accessible. So in the codesandbox you need to move it to the public folder, so that you can access it in the browser via

https://codesandbox.io/s/l711v6j7v7/sprite.svg

Then you can reference it like this:

<use xlinkHref="/sprite.svg#square" />

See this fork of your codesandbox.



来源:https://stackoverflow.com/questions/53485217/react-and-svg-sprite

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