Html 如何使用源链接 react.js 中的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40834908/
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-29 14:04:25  来源:igfitidea点击:

How to link image in react.js using source

htmlreactjssasszurb-foundation

提问by kavin Rakshan

I am working on a react.js website and I want to link a image (logo) to the website. See folder structure

我在 react.js 网站上工作,我想将图像(徽标)链接到该网站。查看文件夹结构

enter image description here

在此处输入图片说明

My image code for the footer logo is

我的页脚徽标的图像代码是

<img className="img-responsive" src="public/assets/image/img/footer-logo.jpg" alt="logo"/>

But the image is not visible on the website when I run it. Any solutions??

但是当我运行它时,该图像在网站上不可见。有什么解决办法吗??

回答by Kafo

If you are using webpack and assuming you are in one of the components as displayed in the image then do:

如果您正在使用 webpack 并假设您在图像中显示的组件之一中,请执行以下操作:

import logo from '../../public/assets/image/img/foorter-logo.jpg';
<img className="img-responsive" src={logo} alt="logo"/>

If you want to stick to what you have then you can do:

如果你想坚持你所拥有的,那么你可以这样做:

<img className="img-responsive" src="../../public/assets/image/img/footer-logo.jpg" alt="logo"/>

回答by Shubham Khatri

You image src url need to be relative to the file you are using it in. So You need to use it like ../../public/assets/image/img/footer-logo.jpg.

你的图像 src url 需要相对于你正在使用它的文件。所以你需要像../../public/assets/image/img/footer-logo.jpg.

Also in react you need to enclose your source within curly brackets

同样在反应中,您需要将源代码括在大括号中

<img className="img-responsive" src={"../../public/assets/image/img/footer-logo.jpg"} alt="logo"/>

Also if you are using webpack you need to use require with the image src url like

此外,如果您使用 webpack,则需要将 require 与图像 src url 一起使用,例如

<img className="img-responsive" src={require("../../public/assets/image/img/footer-logo.jpg")} alt="logo"/>

I hope it helps :)

我希望它有帮助:)

回答by Callat

Ran into a similar bug working on a simple Gatsby test. My path was like: Image of problem

在进行简单的 Gatsby 测试时遇到了类似的错误。我的路径是这样的: 问题图片

To resolve as @Kafo stated:

如@Kafo 所述解决:

  1. Give your image a named import
  2. Wrap that in curly braces as the value of src
  1. 为您的图像命名导入
  2. 把它用花括号括起来作为 src 的值

My result: Result

我的结果: 结果