admin管理员组

文章数量:1332889

I am trying to change the background color of html body to red with a button click, but i only know how to do it with an element that is already inside body, not the body itself.

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>
    );
  }
}

As you can see, i added style={{backgroundColor: this.state.bgColor}} to div, but i can't add it inside body since it's not in this file. Any help?

I am trying to change the background color of html body to red with a button click, but i only know how to do it with an element that is already inside body, not the body itself.

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>
    );
  }
}

As you can see, i added style={{backgroundColor: this.state.bgColor}} to div, but i can't add it inside body since it's not in this file. Any help?

Share Improve this question edited Mar 7, 2019 at 19:41 Erik Philips 54.7k11 gold badges131 silver badges156 bronze badges asked Mar 7, 2019 at 18:59 PleinairPleinair 4499 silver badges23 bronze badges 3
  • 3 document.body.style.backgroundColor = 'red'; – Nick Commented Mar 7, 2019 at 19:02
  • Use a document selector like document.querySelector('body') document.getElementById('#body_id'), etc. – mhatch Commented Mar 7, 2019 at 19:05
  • 2 While most answers will probably tell you to change the backgroundColor, it's a poor choice because you're mixing presentation with logic. That is when the color changes, and another programmer wants to change it, there is not easy answer. Instead you should create a css class that does what you need and add/remove that class from the body html element. – Erik Philips Commented Mar 7, 2019 at 19:39
Add a ment  | 

2 Answers 2

Reset to default 6

It is usually a good practice to manipulate the DOM inside lifecycle methods See doc here. If this is important to you, you could use ponentDidUpdate lifecycle method on your App.js ponent and from there use standard dom manipulation to find the body and update its background color. You can also check in the method to ensure that the previous state and current state changed before acting on it. It could look something like this:

class App extends Component {

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

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

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

Here's an example of manipulating the body within a React ponent, adapted from Frederic Caplette's answer remending to do so in lifecycle methods. However, I do agree with Erik Philips's ment above that this kind of manipulation is better done via adding/removing CSS classes. Using CSS classes decouples details of the styles from the ponent logic and enables extensibility without affecting that logic.

const docBody = document.querySelector('body');

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {bgColored: false};
    this.colorBackground = this.colorBackground.bind(this);
    this.clearBackground = this.clearBackground.bind(this);
  }
  
  colorBackground() {
    this.setState({bgColored: true});
  }
  
  clearBackground() {
    this.setState({bgColored: false});
  }
  
  ponentDidUpdate(prevProps, prevState) {
    const { bgColored } = this.state;
    const className = 'redBg';

    if(prevState.bgColored !== bgColored){
      bgColored ?
        docBody.classList.add(className) :
        docBody.classList.remove(className);
    }
  }
  
  render() {
    return (
      <div>
        <a href="#" onClick={() => this.colorBackground()}>Turn Red</a>
        {' | '}
        <a href="#" onClick={() => this.clearBackground()}>Reset</a>
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));
.redBg {
  background-color: red;
}
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<body>
<div id="root"></div>
</body>

本文标签: javascriptUsing React to change background color of a body element on clickStack Overflow