2016-06-09 53 views
1

這是一個noob問題。我正在使用react-isomorphic-starterkit樣板(https://github.com/RickWong/react-isomorphic-starterkit)開發通用反應應用程序。我會在左側創建一個「固定」側邊欄,其中包含指向右側主容器的子項上呈現的其他頁面的鏈接。這裏是我的代碼:

routes.js如何使用react-router來渲染嵌套組件

module.exports = (
    <Router history={browserHistory}> 
     <Route path="/" component={Main}> 
      <Route path='/inbox' component={Inbox} /> 
     </Route> 
    </Router> 
); 

Main.js

export default class Main extends React.Component { 
    constructor(props, context){ 
     super(props,context); 
     console.log('Main props', props); 
     console.log('Main context', props); 
    } 
    /** 
    * componentWillMount() runs on server and client. 
    */ 
    componentWillMount() { 
     if (__SERVER__) { 
      console.log("Hello server"); 
     } 

     if (__CLIENT__) { 
      console.log("Hello client"); 
     } 
    } 

    /** 
    * Runs on server and client. 
    */ 
    render() { 
     return (
       <App/> 
     ) 
    } 
} 

App.js

class App extends React.Component{ 

    constructor(props, context) { 
    super(props, context); 
    console.log('App props ', props); 
    } 

    render(){ 
    return (
     <div> 
      <Sidebar/> 
      <RightContent /> 
     </div> 
    ) 
    } 

} 

RightContent.js

class RightContent extends React.Component{ 
    render(){ 
    return (
     <div id="b" style={{backgroundColor:"#EEF0F4", width:"100%"}}> 
     <NavBar /> 
     {this.props.children} 
     </div> 
    ) 
    } 
} 

問題是:收件箱組件(一個簡單的<div>)當我點擊側邊欄與<Link to="...">標籤不渲染。我不知道以下事情是否正確:如您所見,在App.js類構造函數中打印出props變量...但輸出爲undefined。但是,在Main.js道具打印正確。 react-router版本大於2.任何人都可以幫我嗎?

回答

1

您不會將道具傳遞給App,因此除非您使用位置上下文,否則它們不會擁有它們。

你應該做的......

render() { 
    return (
    <App {...this.props}/> 
) 
} 

然後,你應該有機會獲得this.props.childrenApp渲染嵌套路線(S)。你需要指定在RightContent太...

render(){ 
    return (
    <div> 
     <Sidebar/> 
     <RightContent> 
     {this.props.children} 
     </RightContent> 
    </div> 
) 
} 

看到文檔教程... https://github.com/reactjs/react-router/blob/master/docs/Introduction.md#with-react-router

+0

太好了!有用!非常感謝! – JohnEisenheim