React router - 在绑定组件之外获取路由道具
React router - get route prop outside of bound component
我定义了一些路由:
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={IndexContainer} />
<Route path="/agence" headerWhite={true} component={AgencyContainer} />
</Route>
</Router>
), document.getElementById('app'));
如您所见,我在 /agence
路线上有一个道具 headerWhite={true}
。我可以通过 this.props.route.headerWhite
在我的 AgencyContainer
组件中访问它。但我想要的是能够在我的 App
组件中访问它。有简单的方法吗?
我想要实现的是将 headerWhite
道具传递给我的 Header
组件,该组件在我的 App
组件中呈现,因为它必须出现在网站的每个页面上.
非常感谢。
我通过执行以下操作解决了问题:
import React from 'react';
import Page from './Page';
import Header from './Header';
function getCurrentRoute(router, routes) {
const currentRoute = routes.filter(route => route.path && router.isActive(route.path, true));
return currentRoute[0];
}
function App(props, context) {
const currentRoute = getCurrentRoute(context.router, props.routes);
return (
<Page>
<Header headerWhite={currentRoute.headerWhite} />
{props.children}
</Page>
)
}
App.contextTypes = {
router: React.PropTypes.object.isRequired
};
export default App;
仍然,它解决了我的问题,但我不知道是否有更好的方法。所以如果有人有更好的解决方案,请给出,我会接受你的回答!
我定义了一些路由:
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={IndexContainer} />
<Route path="/agence" headerWhite={true} component={AgencyContainer} />
</Route>
</Router>
), document.getElementById('app'));
如您所见,我在 /agence
路线上有一个道具 headerWhite={true}
。我可以通过 this.props.route.headerWhite
在我的 AgencyContainer
组件中访问它。但我想要的是能够在我的 App
组件中访问它。有简单的方法吗?
我想要实现的是将 headerWhite
道具传递给我的 Header
组件,该组件在我的 App
组件中呈现,因为它必须出现在网站的每个页面上.
非常感谢。
我通过执行以下操作解决了问题:
import React from 'react';
import Page from './Page';
import Header from './Header';
function getCurrentRoute(router, routes) {
const currentRoute = routes.filter(route => route.path && router.isActive(route.path, true));
return currentRoute[0];
}
function App(props, context) {
const currentRoute = getCurrentRoute(context.router, props.routes);
return (
<Page>
<Header headerWhite={currentRoute.headerWhite} />
{props.children}
</Page>
)
}
App.contextTypes = {
router: React.PropTypes.object.isRequired
};
export default App;
仍然,它解决了我的问题,但我不知道是否有更好的方法。所以如果有人有更好的解决方案,请给出,我会接受你的回答!