在React.js中加载本地图像 [英] Load local images in React.js

查看:93
本文介绍了在React.js中加载本地图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用create-react-app安装了React.它安装得很好,但是我试图在我的一个组件(Header.js,文件路径:src/components/common/Header.js)中加载图像,但是没有加载.这是我的代码:

I have installed React using create-react-app. It installed fine, but I am trying to load an image in one of my components (Header.js, file path: src/components/common/Header.js) but it's not loading. Here is my code:

import React from 'react'; 

export default () => {
  var logo1 = (
    <img 
      //src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-goose.jpg"
      src={'/src/images/logo.png'}
      alt="Canvas Logo"
    />
  );
  return (
    <div id="header-wrap">
      <div className="container clearfix">
        <div id="primary-menu-trigger">
          <i className="icon-reorder"></i>
        </div>

        <div id="logo">
          <a href="/" className="standard-logo" data-dark-logo='/images/logo-dark.png'>{logo1}</a>
          <a href="/" className="retina-logo" data-dark-logo='/images/logo-dark@2x.png'>
            <img src='/var/www/html/react-demo/src/images/logo@2x.png' alt="Canvas Logo" />
          </a>
        </div>
      </div>
    </div>
  );
} 

如果我在logo1变量中将图像路径写为src={require('./src/images/logo.png')},则会出现错误:

If I write the image path as src={require('./src/images/logo.png')} in my logo1 variable, it gives the error:

无法编译.

Failed to compile.

./src/Components/common/Header.js中的错误

Error in ./src/Components/common/Header.js

未找到模块:/var/www/html/wistful/src/Components/common中的./src/images/logo.png

Module not found: ./src/images/logo.png in /var/www/html/wistful/src/Components/common

请帮助我解决此问题.让我知道我在这里做错了.

Please help me solve this. Let me know what I am doing wrong here.

推荐答案

如果您对创建React App有疑问,建议您阅读其

If you have questions about creating React App I encourage you to read its User Guide.
It answers this and many other questions you may have.

具体来说,要包含本地图像,您有两个选择:

Specifically, to include a local image you have two options:

  1. 这种方法很棒,因为所有资产都由构建系统处理,并且将在生产构建中获取带有哈希值的文件名.如果文件被移动或删除,您也会收到错误消息.

    This approach is great because all assets are handled by the build system and will get filenames with hashes in the production build. You’ll also get an error if the file is moved or deleted.

    不利之处在于,如果您有数百张图片,则可能会很麻烦,因为您无法使用任意导入路径.

    The downside is it can get cumbersome if you have hundreds of images because you can’t have arbitrary import paths.

    1. 通常不建议使用这种方法,但是如果您有数百个图像,并且一次导入一个图像太麻烦了,那就太好了.缺点是您必须考虑缓存清除,并自己当心已移动或已删除的文件.

      This approach is generally not recommended, but it is great if you have hundreds of images and importing them one by one is too much hassle. The downside is that you have to think about cache busting and watch out for moved or deleted files yourself.

      希望这会有所帮助!

      这篇关于在React.js中加载本地图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆