Trying to use React.DOM to set body styles

后端 未结 4 1366
情话喂你
情话喂你 2020-12-08 06:07

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({
  rende         


        
相关标签:
4条回答
  • 2020-12-08 06:40

    A good solution to load multiple atributes from a js class to the document body can be:

    componentWillMount: function(){
        for(i in styles.body){
            document.body.style[i] = styles.body[i];
        }
    },
    componentWillUnmount: function(){
        for(i in styles.body){
            document.body.style[i] = null;
        }
    },
    

    And after you write your body style as long as you want:

    var styles = {
        body: {
            fontFamily: 'roboto',
            fontSize: 13,
            lineHeight: 1.4,
            color: '#5e5e5e',
            backgroundColor: '#edecec',
            overflow: 'auto'
        }
    } 
    
    0 讨论(0)
  • 2020-12-08 06:43

    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;
    }
    
    0 讨论(0)
  • 2020-12-08 06:52

    Even if you can set body styles from react with the provided answer, I prefer if a component is only responsible for setting its own style.

    In my case there was an alternative solution. I needed to change the body backgroundColor. This could easily be achieved without changing the body style in a react component.

    First I added this style to the index.html header.

    <style>
        html, body, #react-app {
            margin: 0;
            height: 100%;
        }
    </style>
    

    Then, in my outermost component, I set the backgroundColor to the needed value and the height to 100%.

    0 讨论(0)
  • 2020-12-08 07:00

    The best way to load or append extra classes is by adding the code in componentDidMount().

    Tested with react and meteor :

    componentDidMount() {
        var orig = document.body.className;
        console.log(orig);  //Just in-case to check if your code is working or not
        document.body.className = orig + (orig ? ' ' : '') + 'gray-bg'; //Here gray-by is the bg color which I have set
    }
    componentWillUnmount() {
        document.body.className = orig ;
    }
    
    0 讨论(0)
提交回复
热议问题