首页 > 解决方案 > 反应在更新时更改 CSS 背景

问题描述

尝试在此 React 应用程序中切换 CSS 背景图像。我已经导入了图片。然后我为导入的图像设置一个变量“图像”,因为点击时迭代增加/减少。

问题是身体背景图像似乎没有更新。我认为背景图像会在 componentDidUpdate 中刷新,因为迭代按钮切换 setState 应该强制渲染。

import Background1 from "../images/bg/1.png";
import Background2 from "../images/bg/3.png";
import Background3 from "../images/bg/4.png";


class UserPreferences extends Component {
  constructor(props) {
    super(props);
    this.state = {
      backgroundNumber: 1
    };
  }

  buttonNumberCalcPlus = () => {
    this.setState({ backgroundNumber: ++this.state.backgroundNumber });
  };

  buttonNumberCalcMinus = () => {
    this.setState({ backgroundNumber: --this.state.backgroundNumber });
  };

  componentDidUpdate() {
    var currentBackground = "Background" + this.state.backgroundNumber;
    console.log(currentBackground);

    var image;

    if (this.state.backgroundNumber == 1) {
      image = Background1;
    } else if (this.state.backgroundNumber == 2) {
      image = Background2;
    } else {
      image = Background3;
    }

    var mainBg = {
      backgroundImage: "url( " + { image } + ")"
    };
    console.log(mainBg);
    document.body.style = { mainBg };
  }

  render() {
    return (
      <div>
        <MainMenuToolbar />
        <h2 className="texttimezonepref">Change background image.</h2>
        <button
          id="next"
          onClick={this.buttonNumberCalcPlus}
          className="addbutton"
        >
          NEXT
        </button>
        <button
          id="prev"
          onClick={this.buttonNumberCalcMinus}
          className="subtractbutton"
        >
          PREV
        </button>
      </div>
    );
  }
}

这是在componentDidUpdate中更改背景的正确方法吗:

var mainBg = {
  backgroundImage: "url( " + { image } + ")"
};


document.body.style = { mainBg };

标签: cssreactjs

解决方案


The document.body.style is not JSX, and does not accept the document.body.style = {{ backgroundImage: "url( " + { image } + ")"}} as you're expecting.

Instead, you want to just apply your style change to the target directly, such as:

document.body.style.backgroundImage = url(image)


推荐阅读