我有一个React应用程序,其主要组件如下所示:
var App = React.createClass({
childContextTypes:{
router: React.PropTypes.func.isRequired
},
getChildContext: function() {
return {router: this.props.router};
},
render: function() {
return (
<Router history={browserHistory}>
<Route path="/" component={Main}>
<IndexRoute component={Index} />
<Route path={About.path} component={About} />
<Redirect from="/auth" to="/auth/login" />
<Route path="auth" component={AuthIndex}>
<Route path="login" component={LoginComponent}/>
<Route path="register" component={RegisterComponent} />
</Route>
</Route>
</Router>
);
}
});
module.exports = App;
我试图从像这样的子组件中引用路由器:
contextTypes: {
router: React.PropTypes.func.isRequired
}
而且:
var router = this.context.router
router.push("/");
然而,在最后一行,我得到TypeError: Cannot read property 'push' of undefined
那么如何使用上下文正确地将React Router传递给子组件?
答案 0 :(得分:1)
在我们使用ReactRouter时,这可以使用Es6
App.contextTypes = {
router: React.PropTypes.object.isRequired
};