Javascript 使用React Router,如何将类分配给HTML元素?
我正在使用React路由器为我的React应用程序进行路由 在某些页面上,我希望整个页面具有特定的背景色。有几种方法可以做到这一点,但一种简单的方法是将class+CSS应用于HTML元素 我该怎么做 index.htmlJavascript 使用React Router,如何将类分配给HTML元素?,javascript,reactjs,react-router,Javascript,Reactjs,React Router,我正在使用React路由器为我的React应用程序进行路由 在某些页面上,我希望整个页面具有特定的背景色。有几种方法可以做到这一点,但一种简单的方法是将class+CSS应用于HTML元素 我该怎么做 index.html <head> <title>My Site</title> <link rel="stylesheet" href="style.css"> </head> <body> <div cl
<head>
<title>My Site</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
</div>
</body>
<script src="main.js"></script>
routes.jsx
var React = require('react');
var Routes = require('./routes');
React.render(Routes, document.querySelector('.container'));
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;
var React=require('React');
var ReactRouter=require('react-router');
var HashHistory=require('react-router/lib/HashHistory')。默认值;
var Router=ReactRouter.Router;
var Route=ReactRouter.Route;
var-LandingPage=require(“./components/LandingPage”);
var RegisterPage=require(“./组件/寄存器页”);
变量路由=(
)
module.exports=路线;
尽管可以从React组件内部引用
元素,但这样做是一种反模式
您最好制作
组件,将颜色和子组件作为属性
<Fullscreen color='green'>
<LandingPage />
</Fullscreen>
这甚至可以变成一个混音
function BackgroundColorMixin(color) {
return {
componentDidMount: function() {
var html = document.documentElement;
html.backgroundColor = color;
}
};
}
// LandingPage
mixins: [BackgroundColorMixin('green')]
// RegisterPage
mixins: [BackgroundColorMixin('blue')]
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>
);
// 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')]