美文网首页
在react中使用svg,react hooks+ts+webp

在react中使用svg,react hooks+ts+webp

作者: 躺希腊额阿毛 | 来源:发表于2022-09-12 15:15 被阅读0次

创建SvgIcon组件

import React, { useRef, useMemo, useState, useEffect, FC } from 'react'
type ISvg = {
  iconClass: string           // svg文件名
  className?: string
  width?: number
  height?: number
  color?: string
  style?: Record<string, any>
  onClick?: () => void
}

type IImport = {
  default?: Record<string, any>
  [key: string]: any
}

const SvgIcon: FC<ISvg> = (props: any) => {
  const { iconClass, className, width = 16, height = 16, color = '#000', style = {}, onClick } = props
  const [svgModule, setSvgModule] = useState<IImport>()

  const getSvg = async () => {
    // 引入svg的文件
    const svg = await import(`./svg/${props.iconClass}.svg`)
    setSvgModule(svg)
  }

  const iconPath = useMemo(() => {
    if (svgModule && svgModule.default) {
      return `#${svgModule.default.id}`
    }
  }, [iconClass, svgModule])

  const Style = {
    ...style,
    width: `${width}px`,
    height: `${height}px`,
    color, // svg需要设置颜色的地方,改为currentColor
  }

  useEffect(() => {
    getSvg()
  }, [])

  return (
    <svg onClick={onClick} style={Style} className={`svg-icon ${className}`} aria-hidden="true">
      <use xlinkHref={iconPath} />
    </svg>
  )
}

export default SvgIcon

调用SvgIcon组件

import React, { FC } from 'react'
import SvgIcon from '@/components/SvgIcon'
const Demo: FC = () => {
  return (
    <SvgIcon iconClass="tel" width={16} height={16}  color="#ffffff" />
  )
}
export default Demo

webpack.js中的配置

  module: {
    rules: [
      {
        test: /\.(png|gif|jpg|jpeg|svg|woff|ttf|eot)$/i,
        resourceQuery: /\?.*/,
        type: 'asset/inline',
        exclude: [path.resolve('src/svg')],
      },
      {
        test: /\.(png|gif|jpg|jpeg|svg|woff|ttf|eot)$/i,
        type: 'asset/resource',
        exclude: [path.resolve('src/svg')],
      },
      {
        test: /\.(svg)$/,
        loader: 'svg-sprite-loader',
        exclude: [/node_modules/],
        include: [path.resolve('src/svg')],
      },
  ]
}

相关文章

网友评论

      本文标题:在react中使用svg,react hooks+ts+webp

      本文链接:https://www.haomeiwen.com/subject/viasjrtx.html