繁体   English   中英

使用 React Inline Styles 设置背景图像

[英]Setting a backgroundImage With React Inline Styles

我正在尝试访问 static 图像以在 React 的内联backgroundImage属性中使用。 不幸的是,我已经不知道如何做到这一点了。

一般来说,我以为你只是做了如下:

import Background from '../images/background_image.png';

var sectionStyle = {
  width: "100%",
  height: "400px",
  backgroundImage: "url(" + { Background } + ")"
};

class Section extends Component {
  render() {
    return (
      <section style={ sectionStyle }>
      </section>
    );
  }
}

这适用于<img>标签。 有人可以解释两者之间的区别吗?

例子:

<img src={ Background } />工作得很好。

谢谢!

backgroundImage 属性中的花括号是错误的。

可能您正在使用 webpack 和图像文件加载器,所以 Background 应该已经是一个字符串: backgroundImage: "url(" + Background + ")"

你也可以使用下面的 ES6 字符串模板来达到同样的效果:

backgroundImage: `url(${Background})`

内联样式设置任何图像全屏:

style={{  
  backgroundImage: "url(" + "https://images.pexels.com/photos/34153/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350" + ")",
  backgroundPosition: 'center',
  backgroundSize: 'cover',
  backgroundRepeat: 'no-repeat'
}}

如果您使用的是 ES5 -

backgroundImage: "url(" + Background + ")"

如果您使用的是 ES6 -

backgroundImage: `url(${Background})`

基本上在为 backgroundImage 属性添加值的同时删除不必要的花括号会起作用。

您还可以使用require()函数将图像带入组件。

<div style={{ backgroundImage: `url(require("images/img.svg"))` }}>

注意两组大括号 第一组用于进入反应模式,第二组用于表示对象

这个对我有用:

  import Background from '../images/background_image.png';
    
  <div className=...
       style={{
              background: `url(${Background})`,
            }}
    >...</div>

对我来说,工作就是这样

style={{ backgroundImage: `url(${require("./resources/img/banners/3.jpg")})` }}

您可以改用模板文字(用反引号括起来:`...`)。 对于这样的backgroundImage属性:

backgroundImage: `url(${Background})`

对于 ReactJS 的local文件。 尝试

import Image from "../../assets/image.jpg";

<div
style={{ backgroundImage: 'url(' + Image + ')', backgroundSize: 'auto' }}
>Hello
</div>

这是具有内联样式的ReactJS的情况,其中Image是您必须使用路径导入的本地文件。

尝试这个:

style={{ backgroundImage: `url(require("path/image.ext"))` }}

将代码的第 6 行从

  backgroundImage: "url(" + { Background} + ")"

  backgroundImage: "url(" + { Background.src } + ")"

它会起作用。

改为更新到 17.05.22:

backgroundImage: "url(" + { Background } + ")"

做:

backgroundImage: "url(" + Background + ")"

试试这个它在我的情况下有效

backgroundImage: `url("${Background}")`
  1. 将图像复制到您想要查看的 React 组件的文件夹中。
  2. 复制以下代码:
<div className="welcomer" style={{ backgroundImage: url(${myImage}) }}></div>
  1. 使用 CSS 为您的.welcomer指定高度,以便您可以看到所需大小的图像。

有时你的 SVG 会被 React 内联,所以你需要在它周围加上引号:

     backgroundImage: `url("${Background}")`

否则它是无效的 CSS 并且浏览器开发工具将不会显示您已经设置了背景图像。

import React, { PureComponent } from 'react'
import logo from './logo.png';

class Home extends PureComponent {
    render() {
        return (
            <div>
                 <div
                    style={{
                        backgroundImage: `url("https://www.nicesnippets.com/image/imgpsh_fullsize.png")`, backgroundRepeat: 'no-repeat', width: '800px', height: '250px', color: 'blue'
                    }}>
                        Nice Snippets
                </div>
                    <hr />
                    <div
                        style={{
                            backgroundImage: `url(${logo})`, backgroundRepeat: 'no-repeat', width: '100%', height: '250px', color: 'blue'
                        }}>
                        Nice Snippets
                </div>
            </div>
        )
    }
}

export default Home

只需添加所需的文件或网址

<div style={
   {
      backgroundImage: `url(${require("./path_local")})`,      
   }
}
>

或设置在 css base64 图像中,如

div {
  background:
    url('data:image/gif;base64,R0lGODlhZQBhAPcAACQgDxMFABsHABYJABsLA')
    no-repeat
    left center;
}

您可以使用https://www.base64-image.de/进行转换

您可以通过在整个网址上添加反引号来尝试此操作

style={{backgroundImage:url(${val.image || 'http://max-themes.net/demos/grandtour/upload/Tokyo_Dollarphotoclub_72848283-copy-700x466.jpg'} ) }}

如果您使用的是webpack ,则需要编辑webpack.config.js并将其添加到其中

module: {
  rules: [
 {
      test: /\.(png|jpe?g|gif)$/i,

     dependency: { not: ['url'] },
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 8192,
          },
        },
      ],
    },
  ],
}

如果您使用文件加载器来渲染图像,您需要删除它,如下所示:

    {
       test: /\.(png|jpe?g|gif)$/i,
       loader: 'file-loader',
    },

并在您的 css 文件中,而不是使用背景图像,而是使用背景

background: url(Background);

有关带有图像的 webpack 的更多信息,另请参阅: https ://v4.webpack.js.org/loaders/url-loader/

这对我有用

style={{ backgroundImage: url(${require("../assets/pet4.jpeg").default}) }}

对于 ES6,请使用

backgroundImage: `url("${Background}")

你可以试试 usimg

backgroundImage: url(process.env.PUBLIC_URL + "/      assets/image_location")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM