React和SVG精灵 [英] React and SVG sprite

查看:49
本文介绍了React和SVG精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React,并且试图从Sprite加载svg图标.我的精灵是这样的:

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>

然后我将其加载:

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

无结果.我以一个沙箱为例: https://codesandbox.io/s/l711v6j7v7

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

推荐答案

如果要将其作为外部资源引用,则需要使用svg文件的正确URL,并且需要公开访问.因此,在codesandbox中,您需要将其移至公用文件夹,以便您可以通过以下方式在浏览器中访问它:

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" />

查看您的代码框的分叉.

这篇关于React和SVG精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆