React won#39;t load local images(React 不会加载本地图像)
问题描述
我正在构建一个小型 React 应用程序,但我的本地图像无法加载.placehold.it/200x200
之类的图像会加载.我想这可能是服务器的问题?
I am building a small react app and my local images won't load. Images like placehold.it/200x200
loads. I thought maybe it could be something with the server?
这是我的 App.js
Here is my 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:
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')
);
和 server.js:
and 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');
});
推荐答案
在使用 Webpack 时,您需要 require
图像以便 Webpack 处理它们,这可以解释为什么外部图像加载而内部执行不是,所以你需要使用 <img src={require('/images/image-name.png')}/>
将 image-name.png 替换为每个图像的正确图像名称.这样 Webpack 就能够处理和替换源 img.
When using Webpack you need to require
images 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.
这篇关于React 不会加载本地图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:React 不会加载本地图像
基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01