繁体   English   中英

使用React Router,如何为HTML元素分配一个类?

[英]With React Router, how can I assign a class to the HTML element?

我正在使用React Router为我的React应用程序进行路由。

在某些页面上,我希望整个页面具有特定的背景色。 有几种方法可以做到这一点,但是一个简单的方法就是将一个类+ CSS应用于HTML元素。

我怎样才能做到这一点?

的index.html

<head>
  <title>My Site</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
  </div>
</body>
<script src="main.js"></script>

app.jsx

var React = require('react');
var Routes = require('./routes');

React.render(Routes, document.querySelector('.container'));

routes.jsx

var React = require('react');
var ReactRouter = require('react-router');
var HashHistory = require('react-router/lib/HashHistory').default;
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;

var LandingPage = require('./components/landing-page');
var RegisterPage = require('./components/register-page');

var routes = (
  <Router history={new HashHistory}>
    <Route path="/" component={LandingPage}></Route>
    <Route path="/register" component={RegisterPage} />
  </Router>
)

module.exports = routes;

尽管可以从React组件内部引用<html>元素,但这是一种反模式。

制作<Fullscreen />组件(将颜色和子组件作为属性)会更好。

<Fullscreen color='green'>
  <LandingPage />
</Fullscreen>

在内部,该组件看起来像这样。

var Fullscreen = function(props) {
  var children = props.children,
      color = props.color;

  var styles = {
    backgroundColor: color,
    width: '100%',
    height: '100%'
  };

  return (
    <div style={styles}>
      {children}
    </div>
  );
};

如果您将这些组件与React Router一起使用,则创建组件以作为道具传递给<Route />的最简单方法是使用助手功能。

function makeFullscreen(component, color) {
  return (
    <Fullscreen color={color}>
      {component}
    </Fullscreen>
  );
}

然后通过调用该函数来创建路由组件。

var routes = (
  <Router history={new HashHistory}>
    <Route path="/" component={makeFullscreen(LandingPage, 'red')}></Route>
    <Route path="/register" component={makeFullscreen(RegisterPage, 'blue')} />
  </Router>
);

这样,您就不会破坏React层次结构,并且可以将组件嵌入其他页面中,而不必担心它们会更改页面本身的背景颜色。

不建议

当然,如果您不介意使用React,那么您可以直接修改<html>标签。 使用componentDidMount生命周期钩子确保已安装组件,然后获取元素并只需更改背景颜色。

// LandingPage
componentDidMount: function() {
  var html = document.documentElement;
  html.style.backgroundColor = 'green';
}

// RegisterPage
componentDidMount: function() {
  var html = document.documentElement;
  html.style.backgroundColor = 'blue';
}

这甚至可以变成混入。

function BackgroundColorMixin(color) {
  return {
    componentDidMount: function() {
      var html = document.documentElement;
      html.backgroundColor = color;
    }
  };
}

// LandingPage
mixins: [BackgroundColorMixin('green')]

// RegisterPage
mixins: [BackgroundColorMixin('blue')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM