React如何优雅的封装SvgIcon组件
相信使用过vue
的伙伴们,或多或少都接触或使用过vue-element-admin
,其中许多封装都不禁让人拍案叫绝,因为本人之前是vue
入门前端的,所以对vue-element-admin
许多封装印象深刻,现在从vue
转react
之后,一直想把vue-element-admin
里面的封装组件复刻到react
当中使用,这次是SvgIcon
组件的react
封装版本;
第一步:安装svg-sprite-loader
- npm i svg-sprite-loader -D
- yarn add svg-sprite-loader -D
第二步:配置webpack
- {
- test: /.svg$/,
- loader: "svg-sprite-loader",
- include: path.resolve(__dirname, "../src/icons"),
- options: {
- symbolId: "icon-[name]"
- }
- },
- {
- test: /.(eot|woff2?|ttf|svg)$/,
- exclude: path.resolve(__dirname, "../src/icons"), // 不处理 svg类型文件
- use: [
- {
- loader: "url-loader",
- options: {
- name: "[name]-[hash:5].min.[ext]",
- limit: 10000,
- outputPath: "font",
- publicPath: "font"
- }
- }
- ]
- },
第三步:创建icons/svg文件夹,并且加载所有svg文件

index.ts中方法
- const requireAll = (requireContext: __WebpackModuleApi.RequireContext) =>
- requireContext.keys().map(requireContext)
- const req = require.context('./svg', false, /.svg$/)
- requireAll(req)
- export {} // 默认到处,ts如若不导出,会警告
第四步:创建 SvgIcon 组件
- import React from 'react'
- import PropTypes from 'prop-types'
- import './index.scss'
- const SvgIcon = (props: { iconClass: string; svgClass: string; fill: string ;click: MouseEventHandler<HTMLElement>}) => {
- const { iconClass, fill, svgClass,click } = props
- return (
- <i aria-hidden="true" onClick={click}>
- <svg className={`svg-class ${svgClass}`}>
- <use xlinkHref={'#icon-' + iconClass} fill={fill} />
- </svg>
- </i>
- )
- }
- SvgIcon.propTypes = {
- // svg名字
- iconClass: PropTypes.string.isRequired,
- // 自定义类名
- svgClass: PropTypes.string,
- //自定义方法
- click: PropTypes.func,
- // 填充颜色
- fill: PropTypes.string,
- }
- SvgIcon.defaultProps = {
- fill: 'currentColor',
- svgClass: '',
- click: () => {},
- }
- export default SvgIcon
第五步:在组件中使用 SvgIcon
- import React from 'react'
- import SvgIcon from '@/components/SvgIcon'
- const Index = () => {
- return (
- <div>
- <SvgIcon iconClass="矿泉水" />
- </div>
- )
- }
- export default Index
最终效果:

注意可能会遇到的bug
如果按照以上步骤操作的话,图表还是不出来,有可能是webpack中的配置出来问题;
一般来说打印requireAll(req)
出现以下一个数组才算成功,如果不是,你需要检查下你的webpack是否将svg进行其他操作,导致无法正常解析;

出现以下情况,可能你在你的webpack中配置了一些配置项将svg进行base64转码了,导致svg无法正常解析;

此时检查你的webpack:

总结
以上就是个人在react中模拟vue-element-admin封装SvgIcon组件,以后个人会带来更多的组件封装,更多关于React封装SvgIcon组件的资料请关注w3xue其它相关文章!