本篇内容介绍了“React怎么封装SvgIcon组件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
相信使用过vue
的伙伴们,或多或少都接触或使用过vue-element-admin
,其中许多封装都不禁让人拍案叫绝,因为本人之前是vue
入门前端的,所以对vue-element-admin
许多封装印象深刻,现在从vue
转react
之后,一直想把vue-element-admin
里面的封装组件复刻到react
当中使用,这次是SvgIcon
组件的react
封装版本;
npm 安装
npm i svg-sprite-loader -D
yarn 安装
yarn add svg-sprite-loader -D
{
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"
}
}
]
},
index.ts中方法
const requireAll = (requireContext: __WebpackModuleApi.RequireContext) =>
requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /.svg$/)
requireAll(req)
export {} // 默认到处,ts如若不导出,会警告
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
import React from 'react'
import SvgIcon from '@/components/SvgIcon'
const Index = () => {
return (
<div>
<SvgIcon iconClass="矿泉水" />
</div>
)
}
export default Index
最终效果:
如果按照以上步骤操作的话,图表还是不出来,有可能是webpack中的配置出来问题;
一般来说打印requireAll(req)
出现以下一个数组才算成功,如果不是,你需要检查下你的webpack是否将svg进行其他操作,导致无法正常解析;
出现以下情况,可能你在你的webpack中配置了一些配置项将svg进行base64转码了,导致svg无法正常解析;
此时检查你的webpack:
“React怎么封装SvgIcon组件”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。