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



create-react-app应用程序中,我使用的是React Image Gallery。我让用户选择我的一个库,然后将包含图像路径的数组传递给<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中使用相对路径而没有机会在每个图像文件上使用导入语句?

在这一点上,考虑到React中路径的臭名昭著的问题(请参阅此或此或此(,我不认为这是图像库组件的问题,而是一般的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} />
);
}

最新更新