如何在React中动态导入图像? [英] How do I dynamically import images in React?
问题描述
已经在网上看到了几个答案,但是没有明确的解释,解决方案也无效.所以这就是我想要做的:
Have seen a couple of answers online but there are no clear explanations and the solutions don't work. So this is what I am trying to do:
- 我有一个包含许多图像(以千计)的文件夹-当前它保存在
src/assets/images
文件夹下 - 给出一个图像列表作为输入,我想动态渲染这些图像.而不是全部导入,因为鉴于图片数量如此之高,这是不可能的
- I have a folder of MANY images (thousands) - currently it is saved under
src/assets/images
folder - Given a list of images for example as input, I want to render these images dynamically. And not import all because it would be impossible given the insane number of images
这是我当前的实现方式(无效):
This is my current way of implementing it (which does not work):
// for example
const imageList = ['img1', 'img2', 'img3' /*...so on */]
const getImagePath = (image) => {
return `../assets/images/${image}.jpg`
}
function ImagesPage() {
return (
<>
<p>Below should show a list of images</p>
{imageList.map((img) => {
return <img src={require(getImagePath(img))} />
})}
</>
)
}
根据我在网上阅读的内容,这与 webpack 的工作方式有关,并且只有在将确切的字符串路径输入到 require
中时,此方法才有效:
From what I read online, this has something to do with the way webpack works, and this will only work if the exact string path is input into the require
:
// This works:
<img src={require('../assets/images/img1.jpg')} />
// But all these will not work:
<img src={require(getImagePath(img))} />
const img = 'img1.jpg'
<img src={require(`../assets/images/${img}`)} />
有什么想法可以让我动态导入图像来在我上面描述的场景中工作吗?我认为这篇文章对其他寻求答案的人也将很有帮助.
Any idea how I can get this dynamic importing of images to work in the scenario I described above? I think this post will be quite helpful to the others searching for an answer too.
推荐答案
添加.default可以解决问题
Adding .default will do the trick
<img src={require(`../../folder-path/${dynamic-filename}.png`).default} />
这篇关于如何在React中动态导入图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!