简体   繁体   English

如何在ReactJS中设置图片网址

[英]How to set image url in ReactJS

I am trying to set the path of an Image inside a img tag in ReactJS but It is not showing... 我正在尝试在ReactJSimg标记内设置图像的路径,但未显示...

This is what I tried... 这就是我尝试过的...

import React, { Component } from "react";
import { Carousel } from "react-responsive-carousel";
import "react-responsive-carousel/lib/styles/carousel.css";

export default class CarouselComponent extends Component {

  render() {
    return (
      <Carousel
        showArrows
        emulateTouch
        infiniteLoop
        autoPlay
        interval={2000}
        onChange={this._onChange}
        onClickItem={this._onClickItem}
        onThumbClick={this._onClickThumb}
      >
        <div>
    <img src="../images/sample1.jpg" /> {/*not working*/}
          <p className="legend">Welcome to W.W Coders</p>
        </div>
        <div>
          <img src="http://placehold.it/1080x300?" />
          <p className="legend">Faculty of Computing</p>
        </div>
        <div>
          <img src="http://placehold.it/1080x300?" />
          <p className="legend">Faculty of Engineering</p>
        </div>
        <div>
          <img src="http://placehold.it/1080x300?" />
          <p className="legend">Faculty of Business Management</p>
        </div>
      </Carousel>
    );
  }
}

And this is my folder structure 这是我的文件夹结构

文件夹结构

Can someone tell me where I have went wrong? 有人可以告诉我我哪里出问题了吗?

Assuming you are using webpack or a similar bundler for your code compilation, you can use the file-loader to ensure that the image is copied to the compile folder, and you get the path pointing to it as such: 假设您正在使用webpack或类似的捆绑程序进行代码编译,则可以使用文件加载器来确保将映像复制到compile文件夹,并获得指向该映像的路径,如下所示:

import imagePath from '../images/sample.jpg'

...

<img src={imagePath} />

From your project structure, it looks like the public folder is where you should put all your images. 从项目结构,它看起来像public文件夹是你应该把所有的图像。 Any files that are accessible by url directly (like images), should be inside this folder. 可以直接通过url访问的任何文件(如图像)都应位于此文件夹中。 The files inside src and other folders are intended to be built/compiled and not directly accessed via a URL. src和其他文件夹中的文件旨在构建/编译,并且不能直接通过URL访问。

You should move your images folder to be inside the public folder. 你应该将你的images文件夹是里面public文件夹。 So it would be like: 就像这样:

/public/images/sample1.jpg

Then you would access it like: 然后,您将以如下方式访问它:

src="/images/sample1.jpg"

Assuming you are using create-react-app here's some info about the public folder . 假设您正在使用create-react-app这里是关于一些信息public文件夹 It looks like they want you to use a variable for the path, but often you can just use the root ( / ). 看起来他们希望您为路径使用变量,但是通常您只能使用根( / )。

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

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