简体   繁体   English

React.js 上 img 的正确路径

[英]Correct path for img on React.js

I have some problem with my images on my react project.我的 React 项目中的图片有问题。 Indeed I always thought that relative path into src attribute was built on the files architecture事实上,我一直认为 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 处理的任何形式的路由中,所有图像都可以使用相同的路径显示。

In create-react-app relative paths for images don't seem to work.create-react-app ,图像的相对路径似乎不起作用。 Instead, you can import an image:相反,您可以导入图像:

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

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

If you used create-react-app to create your project then your public folder is accessible.如果您使用 create-react-app 来创建您的项目,那么您的公共文件夹是可以访问的。 So you need to add your image folder inside the public folder.因此,您需要将image文件夹添加到公用文件夹中。

public/images/公开/图片/

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

You're using a relative url, which is relative to the current url, not the file system.您使用的是相对 url,它是相对于当前 url 的,而不是文件系统。 You could resolve this by using absolute urls您可以通过使用绝对网址来解决此问题

<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.但是当您部署到 www.my-domain.bike 或任何其他站点时,这并不好。 Better would be to use a url relative to the root directory of the site最好使用相对于站点根目录的 url

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

With create-react-app there is public folder (with index.html ...).使用create-react-app公共文件夹(带有index.html ...)。 If you place your "myImage.png" there, say under img sub-folder, then you can access them through:如果你把你的“myImage.png”放在那里,比如在img子文件夹下,那么你可以通过以下方式访问它们:

<img src={window.location.origin + '/img/myImage.png'} />
  1. Make an images folder inside src(/src/images) And keep your image in it.在 src(/src/images) 中创建一个图像文件夹并将您的图像保存在其中。 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 method work but first one is recommended because its cleaner way and images are handled by webpack during build time.这两种方法都有效,但推荐第一种方法,因为它更简洁,而且图像在构建时由 webpack 处理。

如果图像放在“src”文件夹中,请使用以下内容:

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

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

Adding file-loader npm to 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.为我工作。

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

A friend showed me how to do this as follows:一位朋友向我展示了如何执行此操作,如下所示:

"./" works when the file requesting the image (eg, "example.js") is on the same level within the folder tree structure as the folder "images".当请求图像的文件(例如,“example.js”)在文件夹树结构中与文件夹“images”处于同一级别时,“./”起作用。

Place the logo in your public folder under eg public/img/logo.png and then refer to the public folder as %PUBLIC_URL%:将徽标放在您的公用文件夹中,例如 public/img/logo.png,然后将公用文件夹称为 %PUBLIC_URL%:

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

The use of %PUBLIC_URL% in the above will be replaced with the URL of the public folder during the build.上面 %PUBLIC_URL% 的使用将在构建过程中替换为public文件夹的 URL。 Only files inside the public folder can be referenced from the HTML.只能从 HTML 引用public文件夹中的文件。

Unlike "/img/logo.png" or "logo.png", "%PUBLIC_URL%/img/logo.png" will work correctly both with client-side routing and a non-root public URL.与“/img/logo.png”或“logo.png”不同,“%PUBLIC_URL%/img/logo.png”将在客户端路由和非根公共 URL 中正常工作。 Learn how to configure a non-root public URL by running npm run build .了解如何通过运行npm run build来配置非根公共 URL。

If your page url contains multiple / then in src go back / count minus 1 times.如果您的页面 url 包含多个 / 则在src返回/计数减 1 次。

For example page url http://localhost:3000/play/game/ then src url must be ../your-image-folder/image-name .例如页面 url http://localhost:3000/play/game/然后src url 必须是../your-image-folder/image-name And your your-image-folder must be in public folder.并且您your-image-folder必须在public文件夹中。

I have used it this way and it worked perfectly我以这种方式使用过它并且效果很好

import Product from "../../images/product-icon.png";
import { Icon } from "@material-ui/core";

<Icon>
    <img src={Product} style={{ width: "21px", height: "24px" }} />
</Icon>

I create my app with create-react-app and I use require instruction if I want to change dynamically my image src:我使用create-react-app创建我的应用程序,如果我想动态更改我的图像 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>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM