简体   繁体   English

反应,无法在数组中导入本地图像以循环

[英]React, cannot import local images inside an array to loop over

I am learning React.js and aiming to make a product page, and I have some issues with importing images from my local directory.我正在学习 React.js 并打算制作一个产品页面,但我在从本地目录导入图像时遇到了一些问题。 These are from my actual project, but it's an online editor, but it should be fine because it's the same issue.这些来自我的实际项目,但它是一个在线编辑器,但应该没问题,因为它是同一个问题。 These are my files:这些是我的文件:

在此处输入图像描述

My App.js:我的 App.js:

import "./styles.css";
import Images from "./Images";

export default function App() {
  return (
    <div className="container">
      {Images.map((content) => (
        <div className="product-image">
          <img src={content.image} />
        </div>
      ))}
    </div>
  );
}

My Images.js:我的图像.js:

const Images = [
  {
    id: 1,
    image: "./img/img1.jpg"
  },
  {
    id: 2,
    image: "./img/img2.jpg"
  },
  {
    id: 3,
    image: "./img/img3.jpg"
  }
];

export default Images;

For Image.js , It is weird because if I make the image source to a url format, it works fine.对于Image.js ,这很奇怪,因为如果我将图像源设为 url 格式,它就可以正常工作。 The local directory name shouldn't be a problem because that's where I imported other sources in my project.本地目录名称应该不是问题,因为这是我在项目中导入其他源的地方。 Any helps would be appreciated.任何帮助将不胜感激。

For this to work, you have two choices, either you put your img folder inside public folder and change Images.js to this:为此,您有两个选择,要么将img文件夹放在public文件夹中,然后将Images.js更改为:

const Images = [
  {
    id: 1,
    image: "/img/img1.jpg"
  },
  {
    id: 2,
    image: "/img/img2.jpg"
  },
  {
    id: 3,
    image: "/img/img3.jpg"
  }
];

export default Images;

Or you keep img folder inside src and change Images.js to this:或者您将img文件夹保留在src中并将Images.js更改为:

import img1 from "./img/img1.jpg";
import img2 from "./img/img2.jpg";
import img3 from "./img/img3.jpg";
const Images = [
  {
    id: 1,
    image: img1
  },
  {
    id: 2,
    image: img2
  },
  {
    id: 3,
    image: img3
  }
];

export default Images;

See this Stack Overflow QA to know why it's like this.请参阅此 Stack Overflow QA以了解为什么会这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM