将道具传递给 React-Router 4.0.0 子路由 [英] Passing Props to React-Router 4.0.0 Children Routes
问题描述
我正在尝试将现有的 react-router 3.0.0 应用程序迁移到 4.0.0.在路由器中,我需要将一个额外的非路由相关的 prop
传递给它的子节点.
在以前版本的 react-router 中,有一些有点老套的方法来实现这一点,本文详细介绍.我个人最喜欢的是使用 cloneElement
的这种方法,因为它确保所有的 react-router道具也被复制了:
//react-router 3.0.0 index.js JSX<路由器历史={browserHistory}<Route path="/" component={App}><Route path="/user/:userId" component={User}/><IndexRoute 组件={Home}/></路线></路线>//App 组件 JSX(使用 cloneElement 添加一个 prop)<div className="应用程序">{ cloneElement(props.children, { appState: value }) }
到目前为止,我的新 App 组件如下所示:
//react-router 4.0.0 App 组件 JSX(将路由代码从 index.js 移到这里)<浏览器路由器><div className="应用程序"><完全匹配模式="/" component={Home}/><Match pattern="/user/:userId" component={User}/><Miss component={Home}/>
</BrowserRouter>
将 appState
道具添加到每个 Match
的组件同时保留提供的路由器道具的最佳方法是什么?
可以使用 render
道具代替 component
>.这允许您内联组件定义.
(<User appState={value} {...props}/>)}/>
I'm trying to migrate an existing react-router 3.0.0 app to 4.0.0. Within the router, I need pass an additional non routing-related prop
to its children.
There are a few somewhat hacky ways to accomplish this in previous versions of react-router, detailed in this post. My personal favorite was this method using cloneElement
, since it ensured that all of the react-router props were copied over as well:
// 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>
So far my new App component looks like:
// 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>
What's the best way to add the appState
prop to each of the Match
's components while retaining the provided router props?
<Route>
can take a render
prop instead of a component
. This allows you to inline the component definition.
<Route path='/user/:userId' render={(props) => (
<User appState={value} {...props} />
)} />
这篇关于将道具传递给 React-Router 4.0.0 子路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!