2016-12-06 115 views
8

我想3.0.0应用程序迁移现有反应,路由器4.0.0。在路由器中,我需要将其他与路由无关的prop传递给它的子节点。传递道具反应,路由器4.0.0儿童路由

在之前的react-router版本中,有一些有点冒险的方法来实现这一点,detailed in this post。我个人最喜欢的是this method使用cloneElement,因为它确保所有反应路由器道具被复制,以及:

// 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> 

到目前为止,我的新的应用程序组件的样子:

// 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> 

有什么将appState道具添加到每个Match的组件中的最佳方法,同时保留提供的路由器道具?

回答

20

<Route>可以采取render道具而不是component。这允许您内联组件定义。

<Route path='/user/:userId' render={(props) => (
    <User appState={value} {...props} /> 
)} />