在反应中导入多个文件 [英] Importing multiple files in react

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

问题描述

我正在为我的 React 项目使用 create-react-app.它已经为导入图像配置了 webpack.我希望将多个图像(比如 10 个)从一个图像文件夹导入到一个组件中.最简单的方法是添加多个导入语句,例如 -

I am using create-react-app for my react project. It has got webpack configured for importing images. I wish to import multiple images (say 10) from a images folder into a component. The easiest way of doing this would be to add multiple import statement such as -

import Img0 from '../images/0.png';
import Img1 from '../images/1.png';
import Img2 from '../images/2.png';
import Img3 from '../images/3.png';
import Img4 from '../images/4.png';
import Img5 from '../images/5.png';
import Img6 from '../images/6.png';
...

当我们有多个文件要导入时,上面的代码不是一个好的选择.有没有办法在循环中添加导入语句?我尝试添加 for 循环,但无法修改变量 Img0、Img1 等(使用 ES6 `` 不起作用,因为它将变量转换为字符串)

The above code would not be a good choice when we have multiple files to import. Is there a way to add the import statements in a loop? I tried adding for loop but I was unable to modify the variables Img0, Img1 etc. (using ES6 `` didn't work as it converted the variable to a string)

推荐答案

你不能使用一个单独的 import 语句,因为 importexport 的全部要点是依赖项可以静态确定,即无需执行代码,但您可以这样做:

You can't use a single import statement, because the whole point of import and export that dependencies can be determined statically, i.e. without executing code, but you can do this:

function importAll(r) {
    let images = {};
    r.keys().map(item => { images[item.replace('./', '')] = r(item); });
    return images;
}

const images = importAll(require.context('./images', false, '/.png/'));

<img src={images['0.png']} />

来源.

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

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