我在我的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="" />

其他回答

我用create-react-app创建了我的应用程序,如果我想动态改变我的image src,我使用require指令:

export const MyComponent = () => {
  const [myImg, setMyImg] = useState(require('./path/to/my/img'));

  const handleClick = () => {
    setMyImg(require('./path/to/other/img'));
  }

  return (
    <div>
      <img src={myImg} alt='myImg' />
      <button onClick={handleClick}>Click me!<button/>
    <div>
  )
}

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.

在组件中导入图像

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

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

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

有些老答案行不通,有些答案不错,但不能解释主题,总结如下:

如果image在'public'目录中

例如:\ \ \ a.png图表

在html中:

<img id="imglogo" src="/charts/logo.svg" />

在JavaScript中:

动态地在新img中创建图像:

var img1 = document.createElement("img");  
img1.src = 'charts/a.png';  

动态设置image为现有的img, id为'img1':

document.getElementById('img1').src = 'charts/a.png';

如果image在'src'目录下:

例如:\ src \ logo.svg

在JavaScript中:

import logo from './logo.svg';  
img1.src = logo;  

在jsx:

<img src={logo} /> 

将logo放在公共文件夹中,例如public/img/logo.png,然后引用公共文件夹为%PUBLIC_URL%:

<img src="%PUBLIC_URL%/img/logo.png"/>

在构建过程中,上面的%PUBLIC_URL%的使用将被公用文件夹的URL取代。只有公共文件夹中的文件才能从HTML中引用。

与"/img/logo.png"或"logo.png"不同,"%PUBLIC_URL%/img/logo.png"将正确地用于客户端路由和非根公共URL。学习如何通过运行npm run build配置一个非根公共URL。