Backgroundimage没有反应

kom*_*hal 6 html css reactjs reactcsstransitiongroup react-native

我是新手做出反应并尝试使用内联样式获取背景图像.但它不起作用.

显示错误"url未定义"

  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>
       )
    }
 }
Run Code Online (Sandbox Code Playgroud)

Kra*_*ain 15

面对类似的问题,这对我来说是个窍门

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

诀窍是添加 require


Ros*_*len 12

CSS值始终是字符串.将backgroundImage值包装在引号中以使其成为字符串:

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


Nee*_*ani 10

在 React 中放置像这样的图像的相对路径

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

似乎不起作用,因为它是JSX,您需要导入图像或需要它

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

...

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

...

<div className="container-login100" style={this.styles}>
Run Code Online (Sandbox Code Playgroud)

只需确保将所有图像放入src文件夹中,因为如果使用的话,不支持从src文件夹外部进行相对导入create-react-app

  • 你的解决方案让我摆脱了困扰我两天的问题! (3认同)

小智 8

就我而言,我的 url 上有空格,所以它需要用引号括起来,例如:'url',因为我直接从服务器获得了 url (imagePath)。

<div style={{ backgroundImage: `url('${imagePath}')` }} />
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助某人。


Anc*_*nek 5

我今天偶然发现了这个线程。我需要backgroundImage动态更改属性,所以require不是一个选项。在我的 ElectronJS 应用程序中,我所做的只是:

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

希望这对某人有所帮助:)