如何在 React 中动态导入图像? [英] How do I dynamically import images in React?

查看:52
本文介绍了如何在 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:

  • 我有一个包含 MANY 图像(数千张)的文件夹 - 目前它保存在 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屋!

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