Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

javascript - Trying to use React.DOM to set body styles

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...