Set background in React.js using style

前端 未结 4 1623
情歌与酒
情歌与酒 2021-02-13 18:19

I want to add a background image in React.js by using a style definition, which works:

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


        
相关标签:
4条回答
  • 2021-02-13 18:25

    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

    0 讨论(0)
  • 2021-02-13 18:31

    This works:

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

    0 讨论(0)
  • If you use an image as background, is better to use the 'backgroundImage' property.

    If you use the 'background' property, this may cause issues on reloading the component (e.g. 'cover' attribute will not apply properly).

    Solution proposed:

    let imgUrl = 'images/berlin.jpg'; 
    
    <div className = 'Component-Bg' 
         style = {{ backgroundImage: `url(${imgUrl})`,
                    backgroundSize: 'cover', 
                    backgroundPosition: 'center center',
                    backgroundRepeat: 'no-repeat',
                  }}>
    </div>
    
    0 讨论(0)
  • 2021-02-13 18:51

    Clarifing another answer

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

    0 讨论(0)
提交回复
热议问题