加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React和Webpack:加载和显示图像作为背景图像

发布时间:2020-12-15 20:16:59 所属栏目:百科 来源:网络整理
导读:我正在创建一个类似横幅的组件,图像设置为组件的背景,但我无法让它工作.我尝试了网上发布的不同建议,但没有运气,目前我不确定我的错误是否在反应代码中,或者是没有正确加载文件的webpack. 这是我的文件结构: AppFolder - client/ -- components/ -- data/ -
我正在创建一个类似横幅的组件,图像设置为组件的背景,但我无法让它工作.我尝试了网上发布的不同建议,但没有运气,目前我不确定我的错误是否在反应代码中,或者是没有正确加载文件的webpack.

这是我的文件结构:

AppFolder
 - client/
 -- components/
 -- data/
 -- images/
 ----- banners/
 ------- frontPageBanner2.png
    ------- 
 -- styles/
 -- myApp.js
 -- store.js
    ---------
 - index.html
 - package.json
 - webpack.config.dev.js

这是我的webpack配置:

var path = require('path'); 
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',entry: [
    'webpack-hot-middleware/client','./client/myApp'
  ],output: {
path: path.join(__dirname,'dist'),filename: 'bundle.js',publicPath: '/static/'
  },plugins: [
    new webpack.HotModuleReplacementPlugin(),new webpack.NoErrorsPlugin()
  ],module: {
    loaders: [
    // js
    {
      test: /.js$/,exclude: /node_modules/,loaders: ['babel'],presets: ['es2015','react'],include: path.join(__dirname,'client')
    },// CSS
    { 
      test: /.scss$/,'client'),loader: 'style-loader!css-loader!sass-loader'
    },//    PNG
    {
      test: /.(jpg|png)$/,loader: "url-loader?limit=25000",//loader: 'file?name=[path][name].[ext]',// FontAwesome
    { test: /.woff(2)?(?v=[0-9].[0-9].[0-9])?$/,loader: "url-loader?limit=10000&mimetype=application/font-woff" },{ test: /.(ttf|eot|svg)(?v=[0-9].[0-9].[0-9])?$/,exclude: path.join(__dirname,'client/images'),loader: "file-loader" },// other SVG
    { test: /.svg$/,loader: 'url-loader',query: { mimetype: "image/svg+xml" },'client/images')
    },]
  }
};

以下是我在应用程序中使用它的方式:

export class Banner extends React.Component {
    render() {
        console.log(this.props.banners);
        // = '../images/banners/frontPageBanner.png'
        const bannerImg = this.props.image.backgroundImage;

        var bannerStyle = {
            background: 'url(' + bannerImg + ')',backgroundSize: this.props.image.backgroundSize,backgroundPosition: this.props.image.backgroundPosition,}

        return (
            <section key={this.props.key} className="container hero" style={bannerStyle}>
                <div className="textbox">
                    <h2>{this.props.title}</h2>
                </div>
            </section>
        )
    }
}

这是由此产生的html:

<section class="container hero" style="background: url('../images/banners/frontPageBanner2.png') 100% 100% / contain;">
    ...
</section>

但是没有显示图像.同时打开图像src链接只显示一个空白屏幕.为什么?我该如何解决?

解决方法

您应该传递一个var,这是需要图像的结果,当您需要使用webpack时,它将生成base64内联图像,而不是相对路径.

var DuckImage = require('./Duck.jpg');

var bannerStyle = {
    backgroundImage: 'url(' + DuckImage + ')',}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读