[英]React router - pass props on routes to child components
有人可以告诉我最好的方法吗? 我想将页面标题道具从路线传递到标头子组件中。 这是我的路线:
var sampleApp= React.createClass({
render: function (){
return (
<div className="our-schools-app">
<Header />
<RouteHandler />
<Footer />
</div>
);
},
});
var routes = (
<Route name="app" path="/" handler={OurSchoolsApp}>
<DefaultRoute name="home" handler={HomePage} />
<Route name="add-school" handler={AddSchoolPage} />
<Route name="calendar" handler={CalendarPage} />
<Route name="calendar-detail" path="calendar-detail/:id" handler={CalendarDetailPage} />
<Route name="info-detail" path="info-detail/:id" handler={InfoDetailPage} />
<Route name="info" handler={InfoPage} />
<Route name="news" handler={NewsListPage} />
<Route name="news-detail" path="news-detail/:id" handler={NewsDetailPage} />
<Route name="contacts" handler={ContactPage} />
<Route name="contact-detail" handler={ContactDetailPage} />
<Route name="settings" handler={SettingsPage} />
</Route>
);
Router.run(routes, function(Handler){
var mountNode = document.getElementById('app');
React.render(<Handler /> , mountNode);
});
我想像这样通过prop传递路线中页面的标题:
<Route name="info" handler={InfoPage} pageTitle="Info Page" />
对于我的标头组件:
var Header = React.createClass({
render: function () {
return (
<div className="bar bar-header"
style={this.getStyle()}>
<HomeButton />
<div className="h1 title">{this.props.pageTitle}</div>
</div>
)
}
});
但是道具显示为空,有人可以帮忙吗?
我只是遇到了同样的问题,并在React Router GitHub问题中找到了这个答案 。
它建议将props
传递到Route
组件,并使用this.props.route.*
从组件访问它们。
我只是将if用于我自己的应用程序,发现它非常易于使用。 ( 比接受的答案特别容易 )这是答案中的示例(感谢anjdreas ):
路由:
React.render((
<Router>
<Route path="/" component={RootComp} myprop="foo">
<Route path="foo" component={FooComp}>
<Route path="bar" component={BarComp} />
</Route>
</Route>
</Router>
), document.getElementById('example'));
零件:
class RootComp extends React.Component {
render: {
this.props.route.myprop // == "foo"
}
}
您目前(1.0之前)无法使用React Router做到这一点。 我相信一种推荐的方法是使用包装器组件:
var BaseComponent = React.createClass({
render: function() {
return <p>{this.props.text}</p>
}
});
var FancyComponent = React.createClass({
return <BaseComponent text="fancy!" />
});
var EvenFancierComponent = React.createClass({
return <BaseComponent text="SUPER fancy!" />
});
然后这些路线:
<Route name="standard" handler={BaseComponent} />
<Route name="fancy" handler={FancyComponent} />
<Route name="superfancy" handler={EvenFancierComponent} />
但是在React Router github问题上有关于此主题的讨论,这提供了一个好消息:
我只是想在这里指出,在新的API(请参阅#1158 )中,路由只是普通对象,因此您可以在其上放置任何所需的道具。 您的过渡钩子将获得路线arg,组件将收到this.props.route,因此您应该一切顺利。
好像新的1.0版本处于beta中,因此应该很快推出!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.