使用ReactJS和React Router改变每条路线的页面背景颜色?

时间:2014-08-24 15:44:20

标签: jquery css reactjs react-jsx

使用ReactJS和React Router时,如何在使用新路线时更改浏览器背景颜色?请参阅下面的编辑,了解我在此过程中想出的想法:

我可以在每个页面视图中使用<div>,但我需要在完整的背景上工作,因此完整的浏览器窗口会显示背景。

我玩jQuery,但想知道这是否是解决这个问题的正确方法?我也尝试使用React.DOM.body,但没有使用它:

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

编辑1: 我得到了这个工作,但是...意味着我必须为每个我希望拥有不同背景的页面复制这个CSS类。要使用以下内容包装每个回报:<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%; 
}

编辑2: 这是另一种方式,我更喜欢这个,它需要更少的CSS行,并且在ReactJS组件中更明确。我在DIV上设置了这个CSS:

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

在我的ReactJS组件中使用它:

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 个答案:

答案 0 :(得分:2)

确保React使用React.renderComponent(<Root>, ...)呈现的根组件覆盖整个屏幕。现在只需管理Root#render()函数中的状态,如下所示:

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

请注意,根组件div#fullscreen必须覆盖整个屏幕。