Change page background color with each route using ReactJS and React Router?

喜你入骨 提交于 2019-12-12 12:21:55

问题


How can I change the browsers background color when going to a new route, using ReactJS and React Router? See my EDIT's below for ideas I figured out along the way:

I can get this working on the <div> in each page view, but I need it working on the full background so the full browser window shows the background.

I playing with jQuery, but wondering if that's even the right way to solve this? I'm also trying to use React.DOM.body, but not getting it working:

  render: function() {
    return (
      <div>
        React.DOM.body( {style: background-color: "green"} )
        <MyHeader />
          <this.props.activeRouteHandler/>
      </div>
    );
  }

EDIT 1: I got this working, but... means I have to duplicate this CSS class for every page I want to have a different background. To use just wrap each return with: <div className="my-signup-bkg">:

.my-signup-bkg {
    /*To support older browsers*/
    height: 100%;
    width: 100%;

    /* Set the height to match that of the viewport. */
    height: 100vh;

    /* Set the width to match that of the viewport. */
    width: 100vw;

    background-image: url("../images/mod-yellow-bkg.jpg");
    background-repeat: no-repeat;
    background-size: 100%; 
}

EDIT 2: Here's another way, that I like this better, it requires fewer lines of CSS and is more explicit in the ReactJS component. I set this CSS on a DIV:

.my-page-text {
    /*height: inherit;*/
    padding: 8% 5% 5% 3%;
    /*top: 55px;*/

    /*To support older browsers*/
    height: 100%;
    width: 100%;

    /* Set the height to match that of the viewport. */
    height: 100vh;

    /* Set the width to match that of the viewport. */
    width: 100vw;

    background-repeat: no-repeat;
    background-size: 100%; 
}

And use this in my ReactJS component:

var MyLoginView = React.createClass({
  render: function() {
    var style = { backgroundImage: 'url("static/images/mod-yellow-bkg.jpg")' };

    return (
      <div className="my-page-text" style={style}>
          Do something.
      </div>
    );
  }
});

回答1:


Make sure that the root component that React renders with React.renderComponent(<Root>, ...) covers the full screen. Now simply manage the state in the Root#render() function like this:

getInitialState: function () {
  return { color: "white" };
},

changeColor: function () {
  this.setState({ color: "black" });
},

render: function () {
  var style = { backgroundColor: this.state.color };

  return (
    <div id="fullscreen" style={style}>
       <a onClick={this.changeColor}>change</a>
    </div>
  );
}

Note that the root component, div#fullscreen, must cover the full screen.



来源:https://stackoverflow.com/questions/25473414/change-page-background-color-with-each-route-using-reactjs-and-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!