reactjs - 一起使用 SVGR 和 Material UI
问题描述
我正在尝试使用 SVGR 将我的 svg 转换为反应组件,我需要使用<SvgIcon />
Material UI 并将转换后的组件作为道具传递给它。这还没有错。
但是,SVGR 将这些组件保存在一个名为 svgCom 的文件夹中,例如,在该文件夹内还有index.js
转换后的 svg 组件。
我需要将所有这些组件包装在其中,<SvgIcon>
因此我不必<SvgIcon/>
为每个用例再次包装此图标;到目前为止,我尝试在template.js
SVGR 中添加这个组件,但是在尝试解析时它会抛出一个错误。
这是做这种事情的最好方法还是有更好的方法?如果我的 template.js 有什么问题?
这是我的 Templete.js:
function template(
{ template },
opts,
{ imports, componentName, props, jsx, exports },
) {
return template.ast`
${imports}
import { SvgIcon } from "@material-ui/core";
///////////////////////////////////// error here
const ${componentName} = (${props}) => <SvgIcon component={${jsx}} />
${exports}
`
}
module.exports = template
谢谢你。
解决方案
我们遇到了同样的问题,经过一些研究,我得出了以下解决方案:
const {
identifier,
jsxClosingElement,
jsxElement,
jsxIdentifier,
jsxOpeningElement,
jsxSpreadAttribute,
} = require('@babel/types')
const iconTemplate = ({ template }, _, { componentName, jsx, exports }) => {
const wrappedJsx = jsxElement(
jsxOpeningElement(jsxIdentifier('SvgIcon'), [jsxSpreadAttribute(identifier('props'))]),
jsxClosingElement(jsxIdentifier('SvgIcon')),
[jsx],
false
)
return template.ast`
import React from 'react'
import SvgIcon from '@material-ui/core/SvgIcon'
const ${componentName} = (props) => ${wrappedJsx}
${exports}
`
}
module.exports = iconTemplate
如果您不想{...props}
在<svg>
标签上,则必须禁用该expandProps
选项
推荐阅读
- testng-eclipse - Appium Automationn TestNG 监听器
- webpack - 将 Webpack 4 升级到 5 后,chart.removeListener 不再是一个函数
- nestjs - NestJS 和 TypeORM 的 graphql 问题
- java - android studio中Java类的生命周期
- spring-boot - 将文件写入服务器后,SftpRemoteFileTemplate 未退出方法
- ios - 与 Xcode 断开连接时,UIButton 不会动态更新状态(选定/默认)
- pyspark - 使用 Pyspark 在 redshift 上执行查询
- plot - 朱莉娅:marker_z 需要很多时间
- eclipse-plugin - Eclipse Ease - ReferenceError:未定义“loadModule”
- java - cloud firestore:设置值而不删除另一个值