Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I use React.DOM to change styles on HTML body?

I tried this code and it's not working:

var MyView = React.createClass({
  render: function() {
    return (
      <div>
        React.DOM.body.style.backgroundColor = "green";
        Stuff goes here.
      </div>
    );
  }
});

If you execute this from the browsers console it works (but I need it working in ReactJS code): document.body.style.backgroundColor = "green";

Also see this question for similar but different solution: Change page background color with each route using ReactJS and React Router?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

Assuming your body tag isn't part of another React component, just change it as usual:

document.body.style.backgroundColor = "green";
//elsewhere..
return (
  <div>
    Stuff goes here.
  </div>
);

It's recommended to put it at componentWillMount method, and cancel it at componentWillUnmount:

componentWillMount: function(){
    document.body.style.backgroundColor = "green";
}

componentWillUnmount: function(){
    document.body.style.backgroundColor = null;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...