简体   繁体   English

使用 React Inline Styles 设置背景图像

[英]Setting a backgroundImage With React Inline Styles

I'm trying to access a static image to use within an inline backgroundImage property within React.我正在尝试访问 static 图像以在 React 的内联backgroundImage属性中使用。 Unfortunately, I've run up dry on how to do this.不幸的是,我已经不知道如何做到这一点了。

Generally, I thought you just did as follows:一般来说,我以为你只是做了如下:

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>
    );
  }
}

This works for <img> tags.这适用于<img>标签。 Can someone explain the difference between the two?有人可以解释两者之间的区别吗?

Example:例子:

<img src={ Background } /> works just fine. <img src={ Background } />工作得很好。

Thank you!谢谢!

The curly braces inside backgroundImage property are wrong. backgroundImage 属性中的花括号是错误的。

Probably you are using webpack along with image files loader, so Background should be already a String: backgroundImage: "url(" + Background + ")"可能您正在使用 webpack 和图像文件加载器,所以 Background 应该已经是一个字符串: backgroundImage: "url(" + Background + ")"

You can also use ES6 string templates as below to achieve the same effect:你也可以使用下面的 ES6 字符串模板来达到同样的效果:

backgroundImage: `url(${Background})`

Inline style to set any image full screen:内联样式设置任何图像全屏:

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'
}}

If you are using ES5 -如果您使用的是 ES5 -

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

If you are using ES6 -如果您使用的是 ES6 -

backgroundImage: `url(${Background})`

Basically removing unnecessary curly braces while adding value to backgroundImage property works will work.基本上在为 backgroundImage 属性添加值的同时删除不必要的花括号会起作用。

You can also bring the image into the component by using the require() function.您还可以使用require()函数将图像带入组件。

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

Note the two sets of curly brackets .注意两组大括号 The first set is for entering react mode and the second is for denoting object第一组用于进入反应模式,第二组用于表示对象

It works for me:这个对我有用:

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

对我来说,工作就是这样

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

You can use Template Literals (enclosed with back-tick: `...`) instead.您可以改用模板文字(用反引号括起来:`...`)。 For backgroundImage property like this:对于这样的backgroundImage属性:

backgroundImage: `url(${Background})`

For a local File in case of ReactJS.对于 ReactJS 的local文件。 Try尝试

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

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

This is the case of ReactJS with inline styling where Image is a local file that you must have imported with a path.这是具有内联样式的ReactJS的情况,其中Image是您必须使用路径导入的本地文件。

尝试这个:

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

Change line 6 of your code from将代码的第 6 行从

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

to

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

and it will work.它会起作用。

updated to 17.05.22 instead:改为更新到 17.05.22:

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

do:做:

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

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

backgroundImage: `url("${Background}")`
  1. Copy the image to the React Component's folder where you want to see it.将图像复制到您想要查看的 React 组件的文件夹中。
  2. Copy the following code:复制以下代码:
<div className="welcomer" style={{ backgroundImage: url(${myImage}) }}></div>
  1. Give a height to your .welcomer using CSS so that you can see your image in the desired size.使用 CSS 为您的.welcomer指定高度,以便您可以看到所需大小的图像。

Sometimes your SVG will be inlined by React so you need quotes around it:有时你的 SVG 会被 React 内联,所以你需要在它周围加上引号:

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

otherwise it's invalid CSS and the browser dev tools will not show that you've set background-image at all.否则它是无效的 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

Just add required to file or url只需添加所需的文件或网址

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

Or set in css base64 image like或设置在 css base64 图像中,如

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

You can use https://www.base64-image.de/ for convert您可以使用https://www.base64-image.de/进行转换

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

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

If you are using webpack you need to edit webpack.config.js and add this into it如果您使用的是webpack ,则需要编辑webpack.config.js并将其添加到其中

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

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

if you use file-loader for rendering images you need to delete that like below:如果您使用文件加载器来渲染图像,您需要删除它,如下所示:

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

and in your css file instead of using background-image use background instead:并在您的 css 文件中,而不是使用背景图像,而是使用背景

background: url(Background);

for more information about webpack with images see this also: https://v4.webpack.js.org/loaders/url-loader/有关带有图像的 webpack 的更多信息,另请参阅: https ://v4.webpack.js.org/loaders/url-loader/

This worked for me这对我有用

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

For ES6, please use对于 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