React+ts 的字体图标组件

337 阅读1分钟
  1. 在 public 下 index.html 中引入该文件
<!-- 字体图标地址: -->
<script src="//at.alicdn.com/t/font_2503709_f4q9dl3hktl.js"></script>
  1. index.scss 中添加通过 css 代码
.icon {
  width: 1em; height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
  1. component/icon 封装组件
// 组件 props 的类型
type Props = {
  // icon 的类型
  type: string
  // icon 的自定义样式
  className?: string
  // 点击事件
  onClick?: () => void
}

const Icon = ({ type, className, onClick }: Props) => {
  return (
    <svg
      className={'icon ' + className}
      aria-hidden="true"
      onClick={onClick}
    >
      <use xlinkHref={`#${type}`}></use>
    </svg>
  )
}

export default Icon

组件使用

import Icon from '@/components/Icon/index'

export default function Layout () {
  return <div className="root">
  
<Icon className="someClass" type="icon-icon-test" onClick={() => { console.log('test') }}/>

  </div>
}

image.png

image.png