React 使用 iconfont 实现自己的 SvgIcon 组件

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

效果如下图所示:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值