使用 React 在单击时更改 body 元素的背景颜色?

Ple*_*air 1 javascript reactjs

我试图通过单击按钮将 html body 的背景颜色更改为红色,但我只知道如何使用已经在 body 内部的元素,而不是 body 本身。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bgColor: ""
    };
  }

  boxClick = e => {
    this.setState({
      bgColor: "red"
    });
  };

  render() {
    return (
      <div className="App">
        <article className="experimentsHolder">
          <div
            className="boxClickCss"
            style={{ backgroundColor: this.state.bgColor }}
            onClick={this.boxClick}
          >
            Click Me!
          </div>
        </article>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我添加style={{backgroundColor: this.state.bgColor}}到 div,但我无法将其添加到 body 中,因为它不在此文件中。有什么帮助吗?

Fre*_*tte 5

操作 DOM 中的 DOM 通常是一个很好的做法,lifecycle methods 请参阅此处的文档。如果这对您很重要,您可以componentDidUpdate在 App.js 组件上使用生命周期方法,然后使用标准的 dom 操作来查找主体并更新其背景颜色。您还可以检查方法以确保在对其执行操作之前之前的状态和当前状态已更改。它可能看起来像这样:

class App extends Component {

constructor(props) {
 super(props);
 this.state = {
 bgColor: ""
 }
}

componentDidUpdate(prevProps, prevState){
  const { bgcolor } = this.state;

  if(prevProps.bgColor !== bgColor){
      const bodyElt = document.querySelector("body");
      bodyElt.style.backgroundColor = bgcolor;
    }
}
Run Code Online (Sandbox Code Playgroud)