React.js 上 img 的正确路径

问题描述:

我的 React 项目中的图像有问题.事实上,我一直认为 src 属性的相对路径是建立在文件架构上的

I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute was built on the files architecture

这里是我的文件架构:

components
    file1.jsx
    file2.jsx
    file3.jsx
container
img
js 
... 

但是我意识到路径是建立在 url 上的.在我的一个组件(例如 file1.jsx)中,我有这个:

However I realized that the path is built on the url. In one of my component (for example into file1.jsx) I have this:

localhost/details/2
<img src="../img/myImage.png" /> -> works

localhost/details/2/id
<img src="../img/myImage.png" /> -> doesn't work, images are not displayed

如何解决这个问题?我希望在 react-router 处理的任何形式的路由中,所有图像都可以以相同的路径显示.

How is it possible to solve this problem? I want that in any form of routes handled by react-router, all images can be displayed with the same path.

您使用的是相对 url,它与当前 url 相关,而不是文件系统.您可以使用绝对网址来解决此问题

You're using a relative url, which is relative to the current url, not the file system. You could resolve this by using absolute urls

<img src ="http://localhost:3000/details/img/myImage.png"/>

但是当您部署到 www.my-domain.bike 或任何其他站点时,这并不好.最好使用相对于站点根目录的 url

But that's not great for when you deploy to www.my-domain.bike, or any other site. Better would be to use a url relative to the root directory of the site

<img src="/details/img/myImage.png"/>