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

创建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
  onClick?: () => void
}

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

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

  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 (
    
  )
}

export default SvgIcon

调用SvgIcon组件

import React, { FC } from 'react'
import SvgIcon from '@/components/SvgIcon'
const Demo: FC = () => {
  return (
    
  )
}
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+webpack5)