【问题标题】:Use SVGR and Material UI together一起使用 SVGR 和 Material UI
【发布时间】:2020-11-01 13:22:19
【问题描述】:

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

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

我需要将所有这些组件包装在<SvgIcon> 内,因此我不必为每个用例再次用<SvgIcon/> 包装这个图标; 到目前为止,我尝试在 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

谢谢。

【问题讨论】:

    标签: reactjs svg material-ui svg-rect


    【解决方案1】:

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

    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
    

    如果您不想在&lt;svg&gt; 标记上使用{...props},则必须禁用expandProps 选项

    【讨论】:

    • 另一个选项是在脚本部分的package.json 文件中使用此 CLI 命令。 {"svg": "svgr -d src/@shared/icons --replace-attr-values '#343C49=currentColor, #343c49=currentColor' --ignore-existing public/svgIcons"} 基本上它将 public/svgicon 编译成 @shared/icons 并将它们包装在反应组件中。使用此命令,您可以告诉 Svgr 在 css 中将 [#hexColor] 更改为 currentColor hen,您可以使用 color 属性来更改 Svg 的颜色。
    • 非常感谢。到处寻找以弄清楚如何包装成 SvgIcon,这帮助我做到了。
    猜你喜欢
    • 2020-09-25
    • 2017-10-16
    • 2020-09-10
    • 2015-10-09
    • 1970-01-01
    • 2021-01-14
    • 2022-06-22
    • 2017-10-26
    • 1970-01-01
    相关资源
    最近更新 更多