我在我的react项目上的图像有一些问题。事实上,我一直认为src属性的相对路径是建立在文件体系结构上的

下面是我的文件架构:

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

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

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,所有的图像可以显示相同的路径。


当前回答

在组件中导入图像

import RecentProjectImage_3 from '../../asset/image/recent-projects/latest_news_3.jpg'

并在image src={RecentProjectImage_3}上调用图像名称作为对象

 <Img src={RecentProjectImage_3} alt="" />

其他回答

如果你的页面url包含多个/,那么在src中返回/ count - 1次。

例如页面url http://localhost:3000/play/game/,那么src url必须是../your-image-folder/image-name。你的your-image文件夹必须在公共文件夹中。

一位朋友向我展示了如何做到这一点:

".当请求图像的文件(例如,"example.js")在文件夹树结构中与文件夹"images"在同一层时,/"工作。

Make an images folder inside src(/src/images) And keep your image in it. Then import this image in your component(use your relative path). Like below- import imageSrc from './images/image-name.jpg'; And then in your component. <img title="my-img" src={imageSrc} alt="my-img" /> Another way is to keep images in public folder and import them using relative path. For this make an image folder in public folder and keep your image in it. And then in your component use it like below. <img title="my-img" src='/images/my-image.jpg' alt="my-img" /> Both method work but first one is recommended because its cleaner way and images are handled by webpack during build time.

您使用的是相对url,相对于当前url,而不是文件系统。你可以通过使用绝对url来解决这个问题

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

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

<img src=“/细节/img/myImage.png”/>

如果图像放在src文件夹中,请使用以下方法:

<img src={require('../logo.png')} alt="logo" className="brand-logo"/>