Javascript React 不会加载本地图片

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

React won't load local images

javascriptreactjs

提问by Petrba

I am building a small react app and my local images won't load. Images like placehold.it/200x200loads. I thought maybe it could be something with the server?

我正在构建一个小型反应应用程序,但我的本地图像无法加载。像placehold.it/200x200负载一样的图像。我想也许这可能是服务器的问题?

Here is my App.js

这是我的 App.js

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div className="home-container">
                <div className="home-content">
                    <div className="home-text">
                        <h1>foo</h1>
                    </div>
                    <div className="home-arrow">
                        <p className="arrow-text">
                            Vzdělání
                        </p>
                        <img src={"/images/resto.png"} />
                    </div>
                </div>
            </div>
        );
    }
}

export default App;

index.js:

索引.js:

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Router, Route, Link } from 'react-router';
import { createHistory } from 'history';
import App from './components/app';

let history = createHistory();

render(
    <Router history={history} >
        <Route path="/" component={App} >
            <Route path="vzdelani" component="" />
            <Route path="znalosti" component="" />
            <Route path="prace" component="" />
            <Route path="kontakt" component="" />
        </Route>
        <Route path="*" component="" />
    </Router>,
    document.getElementById('app')
);

and server.js:

和 server.js:

var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(3000, 'localhost', function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});

回答by Thomas

When using Webpack you need to requireimages in order for Webpack to process them, which would explain why external images load while internal do not, so instead of <img src={"/images/resto.png"} />you need to use <img src={require('/images/image-name.png')} />replacing image-name.png with the correct image name for each of them. That way Webpack is able to process and replace the source img.

使用 Webpack 时,您需要require图像以便 Webpack 处理它们,这可以解释为什么外部图像加载而内部图像不加载,因此<img src={"/images/resto.png"} />您不需要使用<img src={require('/images/image-name.png')} />每个图像的正确图像名称替换 image-name.png 。这样 Webpack 就能够处理和替换源 img。

回答by Hawkeye Parker

I started building my app with create-react-app(see "Create a New App" tab). The README.md that comes with it gives this example:

我开始使用create-react-app构建我的应用程序(请参阅“创建新应用程序”选项卡)。它附带的 README.md 给出了这个例子:

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}

export default Header;

This worked perfectly for me. Here's a link to the master doc for that README, which explains (excerpt):

这对我来说非常有效。这是该 README 主文档链接,其中解释了(摘录):

...You can import a file right in a JavaScript module. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the src attribute of an image or the href of a link to a PDF.

To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a data URI instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png...

...您可以直接在 JavaScript 模块中导入文件。这告诉 Webpack 将该文件包含在包中。与 CSS 导入不同,导入文件会为您提供一个字符串值。该值是您可以在代码中引用的最终路径,例如作为图像的 src 属性或指向 PDF 的链接的 href。

为了减少对服务器的请求数量,导入小于 10,000 字节的图像将返回数据 URI 而不是路径。这适用于以下文件扩展名:bmp、gif、jpg、jpeg 和 png...

回答by fandro

Another way to do:

另一种做法:

First, install these modules: url-loader, file-loader

首先,安装这些模块:url-loaderfile-loader

Using npm: npm install --save-dev url-loader file-loader

使用 npm: npm install --save-dev url-loader file-loader

Next, add this to your Webpack config:

接下来,将其添加到您的 Webpack 配置中:

module: {
    loaders: [
      { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
  }

limit: Byte limit to inline files as Data URL

limit:作为数据 URL 的内联文件的字节限制

You need to install bothmodules: url-loaderand file-loader

您需要安装两个模块:url-loaderfile-loader

Finally, you can do:

最后,你可以这样做:

<img src={require('./my-path/images/my-image.png')}/>

You can investigate these loaders further here:

您可以在此处进一步调查这些加载程序:

url-loader: https://www.npmjs.com/package/url-loader

url-loader: https://www.npmjs.com/package/url-loader

file-loader: https://www.npmjs.com/package/file-loader

文件加载器:https: //www.npmjs.com/package/file-loader

回答by Kiszuriwalilibori

Actually I would like to comment, but I am not authorised yet. That is why that pretend to be next answer while it is not.

其实我想评论,但我还没有被授权。这就是为什么假装是下一个答案,而事实并非如此。

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png

function Header() {
// Import result is the URL of your image
  return <img src={logo} alt="Logo" />;

I would like to continue that path. That works smoothly when one has picture one can simple insert. In my case that is slightly more complex: I have to map several pictures it. So far the only workable way to do this I found is as follows

我想继续这条路。当有图片可以简单插入时,这会很顺利。就我而言,这稍微复杂一些:我必须映射几张图片。到目前为止,我发现的唯一可行的方法如下

import upperBody from './upperBody.png';
import lowerBody from './lowerBody.png';
import aesthetics from './aesthetics.png';

let obj={upperBody:upperBody, lowerBody:lowerBody, aesthetics:aesthetics, agility:agility, endurance:endurance}

{Object.keys(skills).map((skill) => {
 return ( <img className = 'icon-size' src={obj[skill]}/> 

So, my question is whether are there simplier ways to process these images? Needless to say that in more general case number of files that must be literally imported could be huge and number of keys in object as well. (Object in that code is involved clearly to refer by names -its keys) In my case require-related procedures have not worked - loaders generated errors of strange kind during installation and shown no mark of working; and require by itself has not worked neither.

所以,我的问题是是否有更简单的方法来处理这些图像?不用说,在更一般的情况下,必须逐字导入的文件数量可能很大,对象中的键数量也可能很大。(该代码中的对象明确涉及通过名称引用 - 它的键)在我的情况下,与 require 相关的程序没有工作 - 加载程序在安装过程中产生了奇怪的错误并且没有显示任何工作标记;并且 require 本身也不起作用。

回答by vancy-pants

I too would like to add to the answers from @Hawkeye Parker and @Kiszuriwalilibori:

我也想补充@Hawkeye Parker 和@Kiszuriwalilibori 的答案:

As was noted from the docs here, it is typically best to import the images as needed.

正如此处的文档所指出的,通常最好根据需要导入图像。

However, I needed many files to be dynamically loaded, which led me to put the images in the public folder (also stated in the README), because of this recommendation below from the documentation:

但是,由于文档中的以下建议,我需要动态加载许多文件,这导致我将图像放在公共文件夹中(也在自述文件中说明):

Normally we recommend importing stylesheets, images, and fonts from JavaScript. The public folder is useful as a workaround for a number of less common cases:

  • You need a file with a specific name in the build output, such as manifest.webmanifest.
  • You have thousands of images and need to dynamically reference their paths.
  • You want to include a small script like pace.js outside of the bundled code.
  • Some library may be incompatible with Webpack and you have no other option but to include it as a tag.

通常我们建议从 JavaScript 导入样式表、图像和字体。public 文件夹可用作一些不太常见的情况的解决方法:

  • 您需要在构建输出中使用具有特定名称的文件,例如 manifest.webmanifest。
  • 您有数以千计的图像,需要动态引用它们的路径。
  • 您想在捆绑代码之外包含一个像pace.js 这样的小脚本。
  • 某些库可能与 Webpack 不兼容,您别无选择,只能将其作为标签包含在内。

Hope that helps someone else! Leave me a comment if I need to clear any of that up.

希望能帮助别人!如果我需要清除任何内容,请给我留言。

回答by adamj

I just wanted to leave the following which enhances the accepted answer above.

我只想留下以下内容,以增强上面接受的答案。

In addition to the accepted answer, you can make your own life a bit easier by specifying an aliaspath in Webpack, so you don't have to worry where the image is located relative to the file you're currently in. Please see example below:

除了接受的答案之外,您还可以通过alias在 Webpack 中指定路径来让自己的生活更轻松,因此您不必担心图像相对于您当前所在文件的位置。请参见下面的示例:

Webpack file:

网络包文件:

module.exports = {
  resolve: {
    modules: ['node_modules'],
    alias: {
      public: path.join(__dirname, './public')
    }
  },
}

Use:

用:

<img src={require("public/img/resto.ong")} />

回答by Kean Amaral

Sometimes you may enter instead of in your image location/src: try

有时您可能会输入而不是在您的图像位置/src:尝试

./assets/images/picture.jpg

instead of

代替

../assets/images/picture.jpg

回答by zdrsoft

src={"/images/resto.png"}

Using of src attribute in this way means, your image will be loaded from the absolute path "/images/resto.png" for your site. Images directory should be located at the root of your site. Example: http://www.example.com/images/resto.png

以这种方式使用 src 属性意味着,您的图像将从您网站的绝对路径“/images/resto.png”加载。图像目录应位于您站点的根目录。示例:http: //www.example.com/images/resto.png

回答by Vinsensius Danny

I am developing a project which using SSR and now I want to share my solution based on some answers here.

我正在开发一个使用 SSR 的项目,现在我想根据这里的一些答案分享我的解决方案。

My goals is to preload an image to show it when internet connection offline. (It may be not the best practice, but since it works for me, that's ok for now) FYI, I also use ReactHooks in this project.

我的目标是预加载图像以在互联网连接离线时显示它。(这可能不是最佳实践,但因为它对我有用,所以现在没问题)仅供参考,我也在这个项目中使用了 ReactHooks。

  useEffect(() => {
    // preload image for offline network
    const ErrorFailedImg = require('../../../../assets/images/error-review-failed.jpg');
    if (typeof window !== 'undefined') {
      new Image().src = ErrorFailedImg;
    }
  }, []);

To use the image, I write it like this

为了使用图像,我是这样写的

<img src="/assets/images/error-review-failed.jpg" />

回答by hazardous

Try changing the code in server.js to -

尝试将 server.js 中的代码更改为 -

app.use(require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: config.output.path
    }));