簡體   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