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

猜你喜欢

转载自blog.csdn.net/kiscon/article/details/116714243