在React.js上更正img的路径

问题描述:

我的反应项目中的图像存在问题。事实上,我一直认为进入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
conainter
img
js 
... 

但是我意识到路径是在网址上构建的。在我的一个组件中(例如进入file1.jsx)我有这个:

However I realized that the path was build 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 works, 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或任何其他网站时,这并不是很好。更好的方法是使用相对于网站根目录的网址

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 />