1. IconFont新建自己的图标库项目
2. 下载项目至本地
将下载的压缩包解压,拷贝 iconfont.js 至自己的项目中,然后通过script标签在 index.html 中引入。
此时在浏览器中 F12 调试查看源码,可以看看到body下多了一个 svg标签, 如下图所示,其中symbol即为项目中的svg元素。
3. 实现 React SvgIcon 图标组件
SvgIcon render 中定义 svg 标签,其内容通过 <use xlinkHref={this.iconName}></use> 引入,组件定义两个getter 方法,iconSize 和 iconName, 分别用来获取 svg 图标的大小和 xlinkHref。定义 color,size, className,style 4个属性,调用方通过这几个属性来控制 svg 的样式。
js代码
import React from 'react'
import PropTypes from 'prop-types'
import './style.css'
class SvgIcon extends React.Component {
static defaultProps = {
iconSize: '2.5em',
svgClass: 'svg-icon'
}
static propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
className: PropTypes.string,
style: PropTypes.object
}
get iconSize (){
let size = this.props.size
let type = typeof size || 'middle'
if('string' === type){
if('small' === size){
return '2em'
}else if('middle' === size){
return '2.67em'
}else{
return '3.33em'
}
}else if('number' === type){
return size + 'em'
}else{
return '2.5em'
}
}
get iconName(){
return `#icon-${this.props.icon}`
}
render(){
const {svgClass, className, style} = this.props
return(
<svg className={`${svgClass} ${className}`}
style={{'fill': this.props.color,'width': this.iconSize, 'height': this.iconSize, ...style}}
aria-hidden="true">
<use xlinkHref={this.iconName}></use>
</svg>
)
}
}
export default SvgIcon
css代码
.svg-icon {
width: 2.67em;
height: 2.67em;
overflow: hidden;
display: inline-table;
vertical-align: -0.3em;
fill: currentColor;
}
4. 使用 SvgIcon 组件
<SvgIcon size={3} icon='home' />
效果如下图所示: