简体   繁体   English

使用样式在 React.js 中设置背景

[英]Set background in React.js using style

I want to add a background image in React.js by using a style definition, which works:我想通过使用样式定义在 React.js 中添加背景图像,该样式定义有效:

let imgUrl = 'images/berlin.jpg'    
let styles = {
        root: {
            backgroundImage: 'url(' + imgUrl + ')',
            overflow: 'hidden',
        },
        ...

在此处输入图片说明

As you can see, the image repeats in x-direction.如您所见,图像在 x 方向重复。 So I wanted to extend it by:所以我想通过以下方式扩展它:

let imgUrl = 'images/berlin.jpg'
let styles = {
    root: {
        backgroundImage: 'url(' + imgUrl + ')',
        backgroundImage: {
            flex: 1,
            resizeMode: 'cover', // or 'stretch'
        },
        overflow: 'hidden',
    },
    ...

But the image is not loaded anymore:但图像不再加载:

在此处输入图片说明

So how to set the background image and adjust it in React.js?那么如何在 React.js 中设置背景图片并进行调整呢?

This works:这有效:

    let imgUrl = 'images/berlin.jpg'
    let styles = {
        root: {
            backgroundImage: 'url(' + imgUrl + ')',
            backgroundSize: 'cover',
            overflow: 'hidden',
        },
        ...

在此处输入图片说明

Clarifing another answer澄清另一个答案

 let imgUrl = 'images/berlin.jpg' let styles = { root: { backgroundImage: `url(${ imgUrl })` backgroundRepeat : 'no-repeat', backgroundPosition: 'center', } }

If you use an image as background, is better to use the 'backgroundImage' property.如果您使用图像作为背景,最好使用 'backgroundImage' 属性。

If you use the 'background' property, this may cause issues on reloading the component (eg 'cover' attribute will not apply properly).如果您使用 'background' 属性,这可能会导致重新加载组件时出现问题(例如,'cover' 属性将无法正确应用)。

Solution proposed:提出的解决方案:

let imgUrl = 'images/berlin.jpg'; 

<div className = 'Component-Bg' 
     style = {{ backgroundImage: `url(${imgUrl})`,
                backgroundSize: 'cover', 
                backgroundPosition: 'center center',
                backgroundRepeat: 'no-repeat',
              }}>
</div>

Have you tried somthing like this :你有没有试过这样的事情:

let imgUrl = 'images/berlin.jpg'
let styles = {
root: {

    background: 'url('+ imgUrl + ') noRepeat center center fixed',
    backgroundSize: 'cover',
}

Inspired from this post: Stretch and scale a CSS image in the background - with CSS only灵感来自这篇文章: 在背景中拉伸和缩放 CSS 图像 - 仅使用 CSS

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

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