从react文件夹中导入所有文件 [英] Importing all files from a folder in react

查看:2884
本文介绍了从react文件夹中导入所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过index.jsx从'icons'中的文件夹导入所有SVG,如下所示:

I am importing all SVG's from a folder in 'icons' through an index.jsx like the following line:

index.jsx:

index.jsx:

export about from './about.svg';

这里是导入:
Button.jsx

Here goes the Import: Button.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,例如我只是在返回方法中调用,一切正常。

Now to get a specific Svg e.g. I just call in the return methode and everything works fine.

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

Now I want to load different SVG's like:

const svgName = 'back';

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

我怎样才能做到这一点?

How can i make this possible?

推荐答案

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

Use React.createElement syntax for dynamic definition of element instead of JSX, as it only works with compile-time identifiers.

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

这篇关于从react文件夹中导入所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆