我有以下结构为我的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路由器最简单和正确的方法是什么?
你也可以结合es6和无状态函数来得到一个更清晰的结果:
import Dashboard from './Dashboard';
import Comments from './Comments';
let dashboardWrapper = () => <Dashboard {...props} />,
commentsWrapper = () => <Comments {...props} />,
index = () => <div>
<header>Some header</header>
<RouteHandler />
{this.props.children}
</div>;
routes = {
component: index,
path: '/',
childRoutes: [
{
path: 'comments',
component: dashboardWrapper
}, {
path: 'dashboard',
component: commentsWrapper
}
]
}
对于react路由器2.x。
const WrappedComponent = (Container, propsToPass, { children }) => <Container {...propsToPass}>{children}</Container>;
在你的路线上…
<Route path="/" component={WrappedComponent.bind(null, LayoutContainer, { someProp })}>
</Route>
确保第3个参数是一个类似于:{checked: false}的对象。