来自 React 中 js 对象的相对图像路径

Relative image paths from js object in React

create-react-app 应用中,我正在使用 React Image Gallery。我让用户 select 我的画廊之一,然后将包含图像路径的数组传递给 <ImageGallery items={ images } /> 组件。如果我使用绝对路径,它会起作用,如下所示:

{'images': 
  [
    { original: 'https://domain.tld/image_01.jpg' },
    { original: 'https://domain.tld/image_02.jpg' } 
  ] 
}

我的文件结构如下:

>src
  >base
   App.js           // this is where the array is assigned to state
  >data
    >containertypes
      >js
       SlideShow.js  // this is where the array is read from props and used in <ImageGallery />
  >img
   image_01.jpg
   image_02.jpg

我试过像这样使用相对路径:

{'images': 
  [
    { original: '../../../img/image_01.jpg' },
    { original: '../../../img/image_02.jpg' } 
  ] 
}

很遗憾,没有用(也试了少一多一‘..’)。我如何在 React 中使用相对路径而没有机会在每个图像文件上使用 import 语句?

此时,考虑到 React 中臭名昭著的路径问题(参见 or or ),我认为这不是图片库组件的问题,而是一般的 React 问题。

将您的图像文件夹“img”从 src/ 移动到 public/ 并添加 process.env.PUBLIC_URL :

import React from 'react';
import ImageGallery from 'react-image-gallery';
import './App.css';

const images = [
  { original: process.env.PUBLIC_URL + '/img/image_01.jpg' },
  { original: process.env.PUBLIC_URL + '/img/image_02.jpg' },
];

export default function App() {
  return (
   <ImageGallery items={images} />
  );
}