開發前端頁面,經常會有很多共用的圖標icon,那么我們把它單獨做成組件,以便后期重復調用!

首先在components 的icons文件夾下創建BaseIcon.js文件。

我們需要先在命令行安裝glamorous 和 prop-types
npm install glamorous 或者 yarn add glamorous
prop-types我們就不多做介紹了,glamorous是我們調用svg並改變path的屬性時比較重要的插件了。
BaseIcon.js具體內容如下:
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,圖下:

序號1中,帶圓底色的心形icon 為多色icon,需要傳兩個顏色。 序號2中 為單色icon ,只需要傳一個顏色就可以
新建單色icon的js文件 如Check.js 跟BaseIcon.js並列(只用color來控制顏色的)注意:我們的svg icon都是20*20大小
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中的內容 就可以了!
帶圓多色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組件就完成了,純屬個人見解,希望對您有幫助...
