react中将svg作成icon组件在其余模块调用

开发前端页面,常常会有不少共用的图标icon,那么咱们把它单独作成组件,以便后期重复调用!javascript

首先在components 的icons文件夹下建立BaseIcon.js文件。前端

 

咱们须要先在命令行安装glamorous 和 prop-typesjava

npm install glamorous 或者 yarn add glamorousreact

prop-types咱们就很少作介绍了,glamorous是咱们调用svg并改变path的属性时比较重要的插件了。npm

BaseIcon.js具体内容以下:app

import React from 'react';
import PropTypes from 'prop-types';
import glamorous from 'glamorous';

class BaseIcon extends React.PureComponent {
 //定义属性类型 static propTypes = { SvgIcon: PropTypes.func.isRequired, color: PropTypes.string, circleColor: PropTypes.string, fontSize: PropTypes.string, }; static defaultProps = { color: '', //字体颜色 circleColor: '#76829E', //多层path时背景颜色 }; render() { const { color, SvgIcon, circleColor, fontSize, } = this.props; if (color === '' && circleColor === '') { return (<SvgIcon {...this.props} />); } const WrappedSvgIcon = glamorous(SvgIcon)({ '> path': { fill: color, width: fontSize, //设置fontSize来改变svg的大小 height: fontSize, //设置fontSize来改变svg的大小 }, '> circle': { fill: circleColor, //设置带圆背景的icon 圆的颜色,下面会给您截图介绍 }, }); return (<WrappedSvgIcon {...this.props} />); } } export default BaseIcon;

区分一下单色icon 和 带圆的多色icon,图下:svg

序号1中,带圆底色的心形icon 为多色icon,须要传两个颜色。 序号2中 为单色icon ,只须要传一个颜色就能够字体

 

新建单色icon的js文件 如Check.js 跟BaseIcon.js并列(只用color来控制颜色的)注意:咱们的svg icon都是20*20大小ui

import React from 'react';
import { Svg, Path } from 'glamorous';

import BaseIcon from './BaseIcon'; // eslint-disable-line

const BaseSvg = props => (
  <Svg width="1em" height="1em" viewBox="0 0 20 20" {...props}>
    <Path fillRule="evenodd" d="M7.288 14.022L3.34 10.074 2 11.414l5.288 5.288L18.65 5.34 17.31 4z" />
  </Svg>
);

export default props => (
  <BaseIcon
    {...props}
    SvgIcon={BaseSvg}
  />
);

添加其余单色icon时 只须要 覆盖fillRule 和 d中的内容 就能够了!this

 

带圆多色icon js文件(一样很BaseIcon.js并列就能够)以下:

import React from 'react';
import { Svg, Path, Circle } from 'glamorous';

import BaseIcon from './BaseIcon'; // eslint-disable-line

const BaseSvg = props => (
  <Svg width="1em" height="1em" viewBox="0 0 20 20" {...props}>
    <Circle cx="9" cy="9" r="9" />
    <Path fillRule="evenodd" d="M9.1 6.283c-.61-1.156-1.787-1.668-3.133-1.43-1.814.32-2.676 2.276-1.855 4.158.928 2.127 3.047 3.63 4.988 4.777 1.94-1.148 4.06-2.65 4.988-4.777.821-1.882-.04-3.837-1.855-4.158-1.346-.238-2.523.274-3.133 1.43z" />
  </Svg>
);

export default props => (
  <BaseIcon
    {...props}
    SvgIcon={BaseSvg}
  />
);

新增的Circle属性 就是背景圆。

icon js文件建立好后,关于icon组件的调用:

单色组件调用以下图:

 

多色圆icon组件调用:(调用方法都同样,只不过比单色icon多了一个circleColor属性来控制圆的颜色)

 

这样 , 公共icon组件就完成了,纯属我的看法,但愿对您有帮助...

相关文章
相关标签/搜索