開發前端頁面,常常會有不少共用的圖標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組件就完成了,純屬我的看法,但願對您有幫助...