我正在尝试将现有的react-router 3.0.0应用程序迁移到4.0.0 . 在路由器中,我需要向其子节点传递一个额外的非路由相关的 prop
.
在以前版本的react-router,detailed in this post中,有一些不太常见的方法可以实现这一点 . 我个人最喜欢的是this method使用 cloneElement
,因为它确保所有的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
道具的最佳方法是什么?
1 回答
<Route>
可以采用render
道具而不是component
. 这允许您内联组件定义 .