我有以下结构为我的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路由器最简单和正确的方法是什么?
根据Rajesh Naroth回答使用带或不带路由器的组件。
class Index extends React.Component {
constructor(props) {
super(props);
}
render() {
const foo = (this.props.route) ? this.props.route.foo : this.props.foo;
return (
<h1>
Index - {foo}
</h1>
);
}
}
var routes = (
<Route path="/" foo="bar" component={Index}/>
);
或者你可以这样做:
export const Index = ({foo, route}) => {
const content = (foo) ? foo : (route) ? route.foo : 'No content found!';
return <h1>{content}</h1>
};
React-router v4 alpha
现在有了一种新的方法,尽管和之前的方法很相似。
import { Match, Link, Miss } from 'react-router';
import Homepage from './containers/Homepage';
const route = {
exactly: true,
pattern: '/',
title: `${siteTitle} - homepage`,
component: Homepage
}
<Match { ...route } render={(props) => <route.component {...props} />} />
附注:这只适用于alpha版本,并且在v4 alpha发布后被删除。在v4 latest中,同样是带有路径和精确props的。
React-lego是一个示例应用程序,它在react-router-4分支的routes.js中包含了这样做的代码