ReactJS应用程序不能加载背景图像

ReactJS app can't load background image

本文关键字:背景 图像 加载 不能 应用程序 ReactJS      更新时间:2023-09-26

我很少遇到我已经找不到答案的问题,但这次我真的被难住了——如果我的问题被证明是愚蠢的或微不足道的,我提前道歉。

我正在构建一个简单的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做三件事:

  1. ../images/pattern更改为哈希,并使其成为仅返回svg路径的模块,如下所示:

    function(module, exports, webpack_require) {

    module.exports = __webpack_require__.p + "32aa2ecb4810e9d55a3b870c0eab59eb.svg";
    

    }

  2. 复制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>
    )
}