【问题标题】:How to set image url in ReactJS如何在 ReactJS 中设置图像 url
【发布时间】:2019-06-18 19:52:54
【问题描述】:

我正在尝试在ReactJS 中的img 标记内设置图像的路径,但它没有显示...

这是我尝试过的......

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>
    );
  }
}

这是我的文件夹结构

谁能告诉我哪里出错了?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

假设您使用 webpack 或类似的捆绑器进行代码编译,您可以使用文件加载器来确保将图像复制到编译文件夹,并且您会得到指向它的路径:

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

...

<img src={imagePath} />

【讨论】:

    【解决方案2】:

    从您的项目结构来看,public 文件夹似乎是您应该放置所有图像的位置。任何可以通过 url 直接访问的文件(如图像)都应该在这个文件夹中。 src 和其他文件夹中的文件旨在构建/编译,而不是通过 URL 直接访问。

    您应该将images 文件夹移动到public 文件夹内。所以它会是这样的:

    /public/images/sample1.jpg
    

    然后你会像这样访问它:

    src="/images/sample1.jpg"
    

    假设您使用的是create-react-app,这里是some info about the public folder。看起来他们希望您使用变量作为路径,但通常您可以只使用根 (/)。

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 2020-01-07
      • 2021-04-03
      • 2017-12-01
      • 2021-10-11
      • 2020-06-05
      • 1970-01-01
      • 2020-10-11
      相关资源
      最近更新 更多