在ReactJS中更改背景图片

时间:2019-09-22 02:23:55

标签: javascript css reactjs

我目前正在开发一个天气应用程序,该应用程序会根据一天中的时间和天气描述来更改背景。我创建了一个处理页面背景样式的状态。

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      city: undefined,
      country: undefined,
      localtime: undefined,
      timezone: undefined,
      temperature: undefined,
      precip: undefined,
      humidity: undefined,
      weather_icon: undefined,
      weather_description: "",
      error: false,
      backgroundStyle: {
        backgroundImage: undefined,
        backgroundColor: 'black',
        backgroundPosition: 'center',
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat'
      }
    };
  }

我还创建了一个处理背景变化逻辑的函数。在其中还有一个数组,其中包含背景图像。例如,

const bgImage = [
      "",
      "'url(img/snowy.jpg)'",
      "'url(img/night.jpg)'",
      "'url(img/sunny.jpg)'",
      "'url(img/stormy.jpg)'",
      "'url(img/sunset.jpg)'",
      "'url(img/night-rain.jpg)'",
      "'url(img/snow-night.jpg)'"
    ]
    // Check for rain
    if (description === 'showers' || description.includes('rain')) {
      if (time >= 20 || (time >= 0 && time < 7)) {
        this.setState({
          backgroundStyle: {
            backgroundImage: bgImage[6]
          }
        });
      } else if (time > 7 && time < 20) {
        this.setState({
          backgroundStyle: {
            backgroundImage: bgImage[0]
          }
        });
      } else {
        this.setState({
          backgroundStyle: {
            backgroundImage: bgImage[0]
          }
        });
      }
    }

在render函数中,我返回一个div并具有样式

<div className="App" style={this.state.backgroundStyle}>

图像无法加载,我不确定我在做什么错。请帮忙。谢谢。

3 个答案:

答案 0 :(得分:1)

一旦您的url()位于“”下,Webpack稍后将无法在运行时找到图像。

尝试使用:

::before

答案 1 :(得分:1)

首先,我强烈建议您将这种静态文件存储在CDN上,这会使您的客户端更轻便!

但是,如果要使用本地图像,则有两种选择。

您可以导入图像文件,并将其与其他任何导入的对象一样使用。

import snowy from '../../snowy.jpg';
import night from '../../night.jpg';
import sunny from '../../sunny.jpg';
import stormy from '../../stormy.jpg';
import sunset from '../../sunset.jpg';
import nightRain from '../../night-rain.jpg';
import snowNight from '../../snow-night.jpg';

const bgImage = [
      "",
      snowy,
      night,
      sunny,
      stormy,
      sunset,
      nightRain,
      snowNight,
]

您需要提供文件夹的相对路径,例如:../../img/snowy.jpg,请记住,相对路径指的是当前写入路径的文件。

编辑:

您还可以使用类似的内容:

const bgImg = `url(${this.state.backgroundStyle.backgroundImage})`

答案 2 :(得分:0)

这是因为您同时将bgImage数组中的字符串用单引号和双引号引起来