ReactJS应用程序不能加载背景图像
ReactJS app can't load background image
我很少遇到我已经找不到答案的问题,但这次我真的被难住了——如果我的问题被证明是愚蠢的或微不足道的,我提前道歉。
我正在构建一个简单的React应用程序,我应该给Home组件一个背景图像,这是一个.svg
文件。然而,图像无法加载-开发工具网络部分说它无法加载图像-但它确实显示在那里,带有散列文件名,所以我猜文件加载器工作。我还使用了react-css-modules。我尝试了几种方法:
React Component v.1
import React from 'react'
import CSSModules from 'react-css-modules'
import styles from '../styles/home.css'
class Home extends React.Component {
render() {
return (
<div className='homeContainer' styleName='homeBg'>
<div className='col-sm-12 text-center'>
<div className="jumbotron col-sm-6 col-sm-offset-3" styleName='transparentBg'>
<h1>Enter Your Location</h1>
<form>
<div className="form-group">
<input type="text" className="form-control" placeholder='Location...' />
</div>
<div className="form-group">
<button className='btn btn-lg btn-submit btn-success' type="submit">Continue</button>
</div>
</form>
</div>
</div>
</div>
);
}
}
export default CSSModules(Home, styles)
下面是CSS模块:
.homeBg {
background-image: url(../images/pattern.svg)
}
...
和我的Webpack配置:
loaders: [
{test: /'.js$/, exclude: '/node_modules/', loader: 'babel-loader'},
{test: /'.css$/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
},
{test: /'.svg$/, loader: 'file-loader'}
]
这是我在组件中尝试的第二种方法:
render() {
const bgImg = require('../images/pattern.svg')
const background = {
backgroundImage: 'url(' + bgImg + ')'
}
return (
<div className='homeContainer' style={background}>
...
但是无论我这样做-图像不加载。它加载在一个常规的<img>
标签,但不是作为背景。我还能尝试什么?提前感谢任何建议!
可不可以试试,在第二个例子中
render() {
const bgImgUrl = // Insert the url for your image here
const background = {
backgroundImage: 'url(' + bgImgUrl + ')';
}
...
}
而不是使用require?根据https://facebook.github.io/react/tips/inline-styles.html,它似乎需要一个实际的url来做到这一点。
感谢所有的建议,但正如我所料,它原来是一个愚蠢的事情关于Bootstrap和一些糟糕的标记结构…
也许,你必须知道什么file-loader
与你的svg。在第二种方法中,file-loader
做三件事:
-
将
../images/pattern
更改为哈希,并使其成为仅返回svg路径的模块,如下所示:function(module, exports, webpack_require) {
module.exports = __webpack_require__.p + "32aa2ecb4810e9d55a3b870c0eab59eb.svg";
}
-
复制svg文件到输出文件夹
要解决你的问题,我认为你可以看看思想输出文件,找出发生了什么你的svg。
你可以在file-load
我会这样做
import img from 'imageURL'
有点像NPM模块
然后做
state = {
img1: img
}
render(){
const imgSize = { width: 100vw, height: 100vh }
return(
<div><img src={this.state.img1} style={imgSize}/></div>
)
}
- 可以在这里为背景图像设置滤镜吗
- 使用 js 将背景图像设置为 HTML
- 如何使用css动画/javascript使具有背景图像的元素出现
- 循环浏览多个身体背景图像
- 背景图像顶部的滚动图像不移动
- 在pdfmake中嵌入背景图像
- 修复选择菜单时的背景图像
- 使用css()设置背景图像;不起作用
- 鼠标悬停时如何居中放大背景图像
- 强制谷歌为javascript背景图像编制索引
- 淡入不带HTML的背景图像
- 具有淡入淡出效果的全背景图像
- 未加载随机背景图像
- 背景图像前显示Javascript警报
- javascript背景图像位置循环
- CSS动画背景图像的过渡越来越暗
- "Ken Burns效应”;悬停背景图像
- 通过ID JavaScript显示随机背景图像
- JavaScript背景图像
- 带有图像和背景图像的ClipTo