我有以下结构为我的React.js应用程序使用React路由器:
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler />
</div>
);
}
});
var routes = (
<Route path="/" handler={Index}>
<Route path="comments" handler={Comments}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
我想把一些属性传递给Comments组件。
(通常我会这样做,如<Comments myprop="value" />)
用React路由器最简单和正确的方法是什么?
对于react路由器2.x。
const WrappedComponent = (Container, propsToPass, { children }) => <Container {...propsToPass}>{children}</Container>;
在你的路线上…
<Route path="/" component={WrappedComponent.bind(null, LayoutContainer, { someProp })}>
</Route>
确保第3个参数是一个类似于:{checked: false}的对象。
你可以通过将它们传递给<RouteHandler>(在v0.13.x中)或v1.0中的Route组件本身来传递道具;
// v0.13.x
<RouteHandler/>
<RouteHandler someExtraProp={something}/>
// v1.0
{this.props.children}
{React.cloneElement(this.props.children, {someExtraProp: something })}
(来自https://github.com/rackt/react-router/releases/tag/v1.0.0的升级指南)
所有子处理程序都将收到相同的一组道具——这可能有用,也可能没用,取决于具体情况。
这可能是在cookie处理程序中使用react-router-dom的最佳方式
在index.js
import React, { Component } from 'react'
import {Switch,Route,Redirect} from "react-router-dom"
import {RouteWithLayout} from "./cookieCheck"
import Login from "../app/pages/login"
import DummyLayout from "../app/layouts/dummy"
import DummyPage from "../app/pages/dummy"
export default ({props})=>{
return(
<Switch>
<Route path="/login" component={Login} />
<RouteWithLayout path="/dummy" layout={DummyLayout} component={DummyPage}
{...props}/>
<Redirect from="/*" to="/login" />
</Switch>
)
}
并使用cookie检查
import React , {createElement} from 'react'
import {Route,Redirect} from "react-router-dom"
import {COOKIE,getCookie} from "../services/"
export const RouteWithLayout = ({layout,component,...rest})=>{
if(getCookie(COOKIE)==null)return <Redirect to="/login"/>
return (
<Route {...rest} render={(props) =>
createElement(layout, {...props, ...rest}, createElement(component,
{...props, ...rest}))
}
/>
)
}