简体   繁体   English

<img>标签没有拉起作为道具传递的图像

[英]<img> tag is not pulling up the image passed as props

I created one data file and I added Img name as one object. [data.js]: https://i.stack.imgur.com/qG385.png In fact, these images are also stored in the Image folder of my project.我创建了一个数据文件,我添加了一个 object. [data.js]: https://i.stack.imgur.com/qG385.png其实这些图片也存放在我项目的Image文件夹中. But when I pass this data through Component as props, the image is not loading up - [Props data]: https://i.stack.imgur.com/AHByK.png [Props]: https://i.stack.imgur.com/66Jqk.png但是当我通过 Component 作为道具传递这些数据时,图像没有加载 - [道具数据]: https://i.stack.imgur.com/AHByK.png [道具]: https://i.stack。 imgur.com/66Jqk.png

Console also shows that the Img data is getting pulled correctly: [Console]: https://i.stack.imgur.com/5Pkbt.png控制台还显示 Img 数据已正确提取:[控制台]: https://i.stack.imgur.com/5Pkbt.png

If I manually enter img address under src the img gets pulled properly.如果我在 src 下手动输入 img 地址,img 将被正确拉取。 Why I am not able to use it using props?为什么我不能使用道具来使用它?

In React, image tags are a bit different.在 React 中,图像标签有点不同。 This isn't really React's fault, but more a problem of where the images will reside on the server after the app is built.这并不是真正的 React 的错,但更多的是在构建应用程序后图像将驻留在服务器上的位置的问题。

Two Ways to Include an Image in a React Component在 React 组件中包含图像的两种方法

With React, since there's a build step, you need a way to include the image.使用 React,由于有一个构建步骤,您需要一种方法来包含图像。 There are 2 main ways to do that.有两种主要方法可以做到这一点。

Option 1: import the image into the component选项 1:将图像import组件

Put the image file somewhere under the src folder.将图像文件放在src文件夹下的某个位置。 This alone will not automatically make it available, so you have to import the image into the React component where you're using it.仅此一项不会自动使其可用,因此您必须将图像导入到您正在使用它的 React 组件中。 Wherever you want to display the image, render your img tag and pass that variable as the src:无论你想在哪里显示图像,渲染你的 img 标签并将该变量作为 src 传递:

import katie from "../../Images/katie-zaferes.png";

function ImageExample () {
   return <img src={katie} alt="Katie profile" />
}

Option 2: Put the image in the public directory方案二:将图片放在public目录

You can put the image file in the public folder (or if this is not Create React App… then any folder that will be copied to the server).您可以将图像文件放在public文件夹中(或者如果这不是 Create React App...那么任何将被复制到服务器的文件夹)。

Then, assuming your server is treating the public folder as the “root” directory (/), then your images will be available relative to that – just like with plain HTML.然后,假设您的服务器将public视为“根”目录 (/),那么您的图像将相对于该目录可用——就像普通的 HTML 一样。

So if you had an image at public/images/wedding-photography.png , you could display that image this way:因此,如果您在public/images/wedding-photography.png有一张图片,您可以这样显示该图片:


function Home() {
  return (
    <div>
      <img src="images/wedding-photography.png" alt="Wedding photography example"/>
    </div>
  );
}

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

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