Reactjs 同时使用SVGR和材质UI
我正在尝试使用SVGR将我的svg转换为react组件,我需要使用Material UI的Reactjs 同时使用SVGR和材质UI,reactjs,svg,material-ui,svg-rect,Reactjs,Svg,Material Ui,Svg Rect,我正在尝试使用SVGR将我的svg转换为react组件,我需要使用Material UI的,并将转换后的组件作为道具传递给它。 这个还没什么问题 但是,, 例如,SVGR将这些组件保存在一个名为svgCom的文件夹中,该文件夹中有index.jsplus转换的svg组件 我需要在中包装所有这些组件,这样我就不必为每个用例再次用包装这个图标; 到目前为止,我试图在SVGR的template.js中添加此组件,但在尝试解析时它会给我带来一个错误 这是做这件事的最好方法还是有更好的方法? 如果是,我的
,并将转换后的组件作为道具传递给它。
这个还没什么问题
但是,,
例如,SVGR将这些组件保存在一个名为svgCom的文件夹中,该文件夹中有index.js
plus转换的svg组件
我需要在
中包装所有这些组件,这样我就不必为每个用例再次用
包装这个图标;
到目前为止,我试图在SVGR的template.js
中添加此组件,但在尝试解析时它会给我带来一个错误
这是做这件事的最好方法还是有更好的方法?
如果是,我的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
函数模板(
{template},
选择,
{导入、组件名称、道具、jsx、导出},
) {
返回模板.ast`
${imports}
从“@material ui/core”导入{SvgIcon}”;
/////////////////////////////////////这里出错
常量${componentName}=(${props})=>
${exports}
`
}
module.exports=模板
谢谢。我们遇到了同样的问题,经过一些研究,我得出了以下解决方案:
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}
,则必须禁用expandProps
选项另一个选项是在脚本部分的package.json
文件中使用此CLI命令<代码>{“svg”:“svgr-d src/@shared/icons--替换属性值'#343C49=currentColor,#343C49=currentColor'--忽略现有的public/svgIcons'}基本上它将public/svgicon编译成@shared/icons,并将它们包装在react组件中。使用此命令,您可以告诉Svgr将[#hexColor]
更改为currentColor
在css中,您可以使用color属性更改Svg的颜色。