Javascript React.js 上 img 的正确路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37644265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:33:15  来源:igfitidea点击:

Correct path for img on React.js

javascriptreactjswebpack

提问by onedkr

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

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

Here my files architecture:

这是我的文件架构:

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

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

但是我意识到路径是建立在 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

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.

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

采纳答案by prekolna

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

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

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

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

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

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

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

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

回答by claireablani

Not trying to answer the question - just a note that in create-react-app, relative paths for images don't seem to work. Instead, you can import an image.

不是试图回答这个问题 - 只是要注意在 create-react-app 中,图像的相对路径似乎不起作用。相反,您可以导入图像。

import logo from './logo.png' // relative path to image 

class Nav extends Component { 
    render() { 
        return ( 
            <img src={logo} alt={"logo"}/> 
        )  
    }
}

回答by Rubel hasan

If you used create-react-app to create your project then your public folder is accessible. So you need to add your imagefolder inside the public folder.

如果您使用 create-react-app 创建您的项目,那么您的公共文件夹是可访问的。因此,您需要将image文件夹添加到公用文件夹中。

public/images/

公开/图片/

<img src="/images/logo.png" />

<img src="/images/logo.png" />

回答by Dima Gershman

With create-react-appthere is publicfolder (with index.html...). If you place your "myImage.png" there, say under imgsub-folder, then you can access them through:

随着create-react-app公共文件夹(与index.html的...)。如果你把你的“myImage.png”放在那里,比如在img子文件夹下,那么你可以通过以下方式访问它们:

<img src={window.location.origin + '/img/myImage.png'} />

回答by Mustkeem K

  1. 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" />

  2. 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 methods work but first one is recommended because its cleaner way and images are handled by webpack during build time.

  1. 在 src(/src/images) 中创建一个图像文件夹并将您的图像保存在其中。然后在您的组件中导入此图像(使用您的相对路径)。如下图——

    import imageSrc from './images/image-name.jpg';

    然后在您的组件中。

    <img title="my-img" src={imageSrc} alt="my-img" />

  2. 另一种方法是将图像保存在公共文件夹中并使用相对路径导入它们。为此,在公共文件夹中创建一个图像文件夹并将您的图像保存在其中。然后在您的组件中使用它,如下所示。

    <img title="my-img" src='/images/my-image.jpg' alt="my-img" />

    这两种方法都有效,但推荐第一种方法,因为它更简洁,而且图像在构建时由 webpack 处理。

回答by Sodhi saab

in my case following code works too.

在我的情况下,以下代码也有效。

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

回答by Manohar Reddy Poreddy

Some older answers din't work, others are good but won't explain the theme, in summary:

一些较旧的答案不起作用,其他答案很好,但不会解释主题,总而言之:

If image is in 'public' directory

如果图像在“公共”目录中

Example: \public\charts\a.png

例子: \public\charts\a.png

In html:

在 HTML 中:

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

In JavaScript:

在 JavaScript 中:

Create image to new img, dynamically:

动态创建图像到新的 img:

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

Set image to existing img with id as 'img1', dynamically:

动态地将图像设置为 id 为 'img1' 的现有 img:

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

If image is in 'src' directory:

如果图像在“src”目录中:

Example: \src\logo.svg

例子: \src\logo.svg

In JavaScript:

在 JavaScript 中:

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

In jsx:

在 jsx 中:

<img src={logo} /> 

回答by Treefish Zhang

Adding file-loader npmto webpack.config.js per its official usage instruction like so:

根据官方使用说明将文件加载器 npm添加到 webpack.config.js,如下所示:

config.module.rules.push(
    {
        test: /\.(png|jpg|gif)$/,
        use: [
            {
                loader: 'file-loader',
                options: {}
            }
        ]
    }
);

worked for me.

为我工作。

回答by Md. Rana

Import Images in your component

在组件中导入图像

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

And call the image name on image src={RecentProjectImage_3}as a object

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

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

回答by AdamJSim

A friend showed me how to do this as follows:

一位朋友向我展示了如何执行此操作,如下所示:

"./" works when the file requesting the image (e.g., "example.js") is on the same level within the folder tree structure as the folder "images".

当请求图像的文件(例如,“example.js”)在文件夹树结构中与文件夹“images”处于同一级别时,“./”起作用。