使用 ReactJS 和 React Router 更改每个路由的页面背景颜色?

2024-01-12

使用 ReactJS 和 React Router 前往新路线时如何更改浏览器背景颜色?请参阅下面我的编辑,了解我一路上想到的想法:

我可以让它工作<div>在每个页面视图中,但我需要它在完整背景上工作,以便完整浏览器窗口显示背景。

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

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

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

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

确保 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,必须覆盖全屏。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ReactJS 和 React Router 更改每个路由的页面背景颜色? 的相关文章

随机推荐