首页 > 解决方案 > 一起使用 SVGR 和 Material UI

问题描述

我正在尝试使用 SVGR 将我的 svg 转换为反应组件,我需要使用<SvgIcon />Material UI 并将转换后的组件作为道具传递给它。这还没有错。

但是,SVGR 将这些组件保存在一个名为 svgCom 的文件夹中,例如,在该文件夹内还有index.js转换后的 svg 组件。

我需要将所有这些组件包装在其中,<SvgIcon>因此我不必<SvgIcon/>为每个用例再次包装此图标;到目前为止,我尝试在template.jsSVGR 中添加这个组件,但是在尝试解析时它会抛出一个错误。

这是做这种事情的最好方法还是有更好的方法?如果我的 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

谢谢你。

标签: reactjssvgmaterial-uisvg-rect

解决方案


我们遇到了同样的问题,经过一些研究,我得出了以下解决方案:

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选项


推荐阅读