2017-09-26 22 views
1

我們已經知道如何挑選和動態渲染組件:是否可以在react-router-dom中給動態組件<Route>?

import CompA from './CompA'; 
import CompB from './CompB'; 

var componentSet = { 
'compa': CompA, 
'compb': CompB 
} 

var type = 'compa' 
var TargetComp = componentSet[type]; 
... 
return <TargetComp /> 

但我沒有成功嘗試將其與<Route>組件整合時:

class DynamicRoute extends Component { 
    render() { 
     return (
      <Route path="/compa" render={()=> <TargetComp /> }/> 
     ); 
    } 
} 
// Error message: 
// Content.render(): A valid React element (or null) must be returned.- 
// You may have returned undefined, an array or some other invalid object. 

欣賞任何幫助!

回答

0

這是用於v4嗎?我通常使用組件道具而不是渲染。這會工作嗎?

<Route path="/compA" component={TargetComp}/>

+0

是的,我使用v4,不幸的是我已經嘗試過,但它不工作。 – Carr

+0

我想你有一個簡單的輸入錯誤 此行'''var TargetComp = componentSet [compa];'''會給出一個錯誤,除非有更多的代碼被隱藏,因爲compa沒有在任何地方定義爲變量......所以componentSet [compa]可能會評估將返回null的componentSet [undefined]。將其更改爲'componentSet [type]' –

+0

謝謝,我只是正確的!但它只是在示例中的錯字顯示在這裏。 – Carr

0

如果你想在組件訪問路徑屬性(如matchlocationhistory像在組件的代碼this.props.history)通過Route渲染你可以通過道具到組件以這樣的方式

<Route path="/compA" component={(props) => (<compA {...props} myProp={this.state.myProp} />) } /> 
相關問題