Backgroundimage is not working in react

≯℡__Kan透↙ 提交于 2019-11-29 14:53:27

问题


I am new to react and trying to get background image with inline styling. But it's not working.

Showing error "url is not defined"

  render() {
    return (
        <div className="phase1" 
             style ={ { backgroundImage: url('https://lh3.googleusercontent.com/MOf9Kxxkj7GvyZlTZOnUzuYv0JAweEhlxJX6gslQvbvlhLK5_bSTK6duxY2xfbBsj43H=w300') } }>

            <input id="search" 
                   type="text" 
                   placeholder={this.state.search} 
                   onChange={this.updateSearch.bind(this)}/>
            &nbsp; &nbsp;&nbsp; &nbsp;

            <Link className="button1" to="Form"> + </Link>
        </div>
       )
    }
 }

回答1:


CSS values are always strings. Wrap the backgroundImage value in quotation marks to make it a string:

<div className="phase1" style ={ { backgroundImage: "url('https://lh3.googleusercontent.com/MOf9Kxxkj7GvyZlTZOnUzuYv0JAweEhlxJX6gslQvbvlhLK5_bSTK6duxY2xfbBsj43H=w300')" } }>



回答2:


Faced a similar problem and this did the trick for me

style={{backgroundImage: 'url(' + require('./images/sword.png') + ')'}}

the trick was adding the require




回答3:


I've stumbled upon this thread today. I was in need to change the backgroundImage property dynamically, so require was not an option. In my ElectronJS app all I did was:

const imageFilePath = './some/dynamic/path/here';
const style = { backgroundImage: `url('file://${imageFilePath}')` };

Hope this helps somebody :)




回答4:


I was battling with this same issue this morning but i was able to fix it with below snippet.

  <div
  className="col-md-4 col-xs-12"
  style={{
    backgroundImage: `url(${require('./path/img.png')})`,
    backgroundPosition: 'center',
    backgroundSize: 'cover',
    backgroundRepeat: 'no-repeat',
  }}
>



回答5:


In React putting relative paths for images like this

<div className="container-login100" style={{ backgroundImage: "url('./folder/images/bg-01.jpg')" }}>

doesn't seems to work as it is JSX, you need to import the image or require it

import BackgroundImage from './../frontend_authentication_copied/images/bg-01.jpg'

...

styles = {
        backgroundImage: `url(${BackgroundImage})`
    }

...

<div className="container-login100" style={this.styles}>

Just make sure you put all the images inside the src folder since relative imports are not supported from outside the src folder if create-react-app is used.



来源:https://stackoverflow.com/questions/38794106/backgroundimage-is-not-working-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!