【问题标题】:Importing all files from a folder in react从反应文件夹中导入所有文件
【发布时间】:2017-04-26 10:43:41
【问题描述】:

我正在通过 index.jsx 从“图标”中的文件夹中导入所有 SVG,如下行:

index.jsx:

export about from './about.svg';

这里是导入: 按钮.jsx

import React from 'react';
import './MenuIcon.scss';
import * as IconID from './icons';

const Button = (props) => {
    return (
        <div className="menu-icon" >
            <div className={'menu-icon__icon-wrapper'}>
                <IconID.about /> // This works great
                <IconID['about'] /> // This does not work
            </div>
        </div>
    );
};

export default Button;

现在获取特定的 Svg,例如我只是调用返回方法,一切正常。

现在我想加载不同的 SVG,例如:

const svgName = 'back';

return (<IconId['back'] />);

我怎样才能做到这一点?

【问题讨论】:

  • 你为什么使用 而不是 ?在属性上使用数组访问器在技术上没有任何问题。 (jsbin.com/jesonafuto/edit?html,js,output)
  • 实际上这就是项目的构建方式,它使用github.com/jhamlet/svg-react-loader 将svg 加载到浏览器。我必须重组项目以这种方式加载 svg。如果没有其他选择,我会使用 url-loader 并将 svg 加载到 img 但如果有其他选项,那就太好了

标签: reactjs import jsx


【解决方案1】:

使用React.createElement 语法来动态定义元素而不是 JSX,因为它只适用于编译时标识符。

React.createElement(IconId.back, {...props}, [...children])

【讨论】:

    【解决方案2】:

    你可以在这里使用上下文

    const importAll = (r) => {
      return r.keys().map(r);
    };
    
    const allData = importAll(
      require.context("./icons", false, /\.svg$/)
    )
    

    【讨论】:

      猜你喜欢
      • 2019-08-25
      • 2016-11-04
      • 2016-10-14
      • 2015-03-12
      • 2020-02-06
      • 2018-07-11
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      相关资源
      最近更新 更多