React项目中使用svg组件

使用react-svg模块

  1. 安装依赖 yarn add -D react-svg
  2. 新建index.js文件

import React from 'react';
import { ReactSVG } from 'react-svg';

function getAll(context) {
  return context.keys().reduce((o, modulePath, i) => {
    o[modulePath.replace(/.\/|.svg/g, '')] = props => {
      return <ReactSVG src={context.keys().map(context)[i]} {...props} />;
    };
    return o;
  }, {});
}

// 当前组件下的icons目录,存放svg图标
export default getAll(require.context('./icons', false, /\.svg$/));

3.使用

import SvgIcon from '@/components/SvgIcon';

// icons目录下名为Upload.svg图标
<SvgIcon.Upload />

使用svg-sprite-loader模块

  1. 安装依赖 yarn add -D svg-sprite-loader
  2. 配置loader
{
  test: /\.svg$/,
  loader: 'svg-sprite-loader',
  include: path.resolve(__dirname, '../src/icons'), // 处理指定svg的文件
  options: {
    symbolId: 'icon-[name]'
  }
},
  1. 在主入口导入所有icons
import './icons';
  1. 编写SvgIcon组件
import React from 'react';
import PropTypes from 'prop-types';

const SvgIcon = props => {
  const { iconClass } = props;
  return (
    <svg aria-hidden="true" className="svg-icon" >
      <use xlinkHref={"#icon-" + iconClass}  />
    </svg>
  );
};

SvgIcon.propTypes = {
  iconClass: PropTypes.string.isRequired
};

export default SvgIcon;

  1. 使用
import SvgIcon from '@/components/SvgIcon';

<SvgIcon iconClass="upload" />  
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值