我正在尝试将现有的react-router 3.0.0应用程序迁移到
4.0.0.在路由器中,我需要向其子节点传递一个额外的非路由相关的prop.
在以前版本的react-router,detailed in this post中有一些有点hacky方法可以实现这一点.我个人最喜欢的是使用cloneElement的this method,因为它确保所有的react-routers道具都被复制了:
// react-router 3.0.0 index.js JSX <Router history={browserHistory} <Route path="/" component={App}> <Route path="/user/:userId" component={User} /> <IndexRoute component={Home} /> </Route> </Routes> // App component JSX (uses cloneElement to add a prop) <div className="App"> { cloneElement(props.children,{ appState: value }) } </div>
到目前为止,我的新App组件如下所示:
// react-router 4.0.0 App component JSX (moved routing code out of index.js and into here) <BrowserRouter> <div className="App"> <Match exactly pattern="/" component={Home} /> <Match pattern="/user/:userId" component={User} /> <Miss component={Home} /> </div> </BrowserRouter>
在保留提供的路由器道具的同时,为每个Match的组件添加appState prop的最佳方法是什么?
<路线>可以采用渲染道具而不是组件.这允许您内联组件定义.
<Route path='/user/:userId' render={(props) => ( <User appState={value} {...props} /> )} />
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。