SVG Sprite

SVG Sprite 作用同 CSS Sprite,也可以有效缩短响应时间;SVG Sprite 有两种模式:injected(注入) 和 extract(提取)。以下为 injected 模式(VD 默认)的实现步骤:

首先,导入 Icon 组件(项目样板默认提供)和相应的 svg 文件:

import Icon from '../Icon';
import add from './images/add.svg';

然后,在 render 里面调用 Icon 组件:

...
render() {
    return (
        <Icon glyph={add} />
    );
}
...

大功告成,最终效果:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0" id="__SVG_SPRITE_NODE__">
<symbol viewBox="0 0 16 16" id="add">
  <path class="st0" d="M11.7 7.3H8.5V3.9c0-.2-.2-.4-.6-.4-.4 0-.6.2-.6.4v3.4H4.1s-.6-.1-.6.5c0 .7.3.7.5.7h3.4v3.6c0 .3-.1.7.5.7s.6-.6.6-.7V8.5h3.1c.1 0 .7 0 .7-.6.1-.7-.6-.6-.6-.6zM8 0C3.6 0 0 3.6 0 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8zm0 14.9c-3.8 0-6.9-3.1-6.9-6.9 0-3.8 3.1-6.9 6.9-6.9s6.9 3.1 6.9 6.9c0 3.8-3.1 6.9-6.9 6.9z"></path>
</symbol>
</svg>
<svg class="icon" width="1" height="1" viewBox="0 0 16 16">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#add">
    </use>
</svg>

So,就可以通过 CSS 来控制 SVG 图标的样式了:

.icon {
    font-size: 16px;
    color: #333;
}

参考:

  1. https://www.w3ctech.com/topic/92
  2. http://www.uisdc.com/svg-icon-part-one

extract(提取)模式:将 SVG 资源提取到单独的文件中。

使用 extract 模式需要修改 Icon 组件代码为:

const Icon = ({glyph, className, width, height}) => (
    <svg className={className} width={width} height={height} viewBox={glyph.viewBox}>
        {/* 如果 svg sprite extract 选项为 false,使用  */}
        {/* <use xlinkHref={`#${glyph.id}`} /> */}
        {/* 否则,使用 */}
        <use xlinkHref={glyph} />
    </svg>
);

并在 项目设置 > 预编译 > Asset 开启 extract 模式:

注意:更改配置后需要退出当前项目,在次打开项目配置才能生效。

最终效果:

<svg class="icon" width="1" height="1" viewBox="0 0 16 16">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/resources/images/sprite.svg#add-usage">
    </use>
</svg>

SVG extract 浏览器支持参考:http://caniuse.com/#feat=svg-fragment

results matching ""

    No results matching ""