2016-03-28 59 views
11

我剛開始學習React,我試着做一個SPA博客,它有一個全球定位的固定標題。React路由器全局標題

import React from 'react'; 
import { render } from 'react-dom'; 
// import other components here 

    render((
     <Router history={browserHistory}> 
     <Route path="/" component={Home} /> 
     <Route path="/About" component={About} /> 
     <Route path="/Contact" component={Contact} /> 
     <Route path="*" component={Error} /> 
     </Router> 
    ), document.getElementById('app')); 

因此,每個路由具有相同的頭文件和我的角度背景,我會使用ui-view之外的頭文件。

它是在每個單獨的頁面組件中導入頁眉組件的好習慣,還是我可以在我的<Router><myHeader/><otherRoutes/></Router>上添加頁眉組件?

更新:

我想用這樣的:

路線組成,在這裏我定義我的路線:

class Routes extends React.Component { 
    render() { 
     return (
      <Router history={browserHistory}> 
       <IndexRoute component={Home} /> 
       <Route path="/studio" component={Studio} /> 
       <Route path="/work" component={Work} /> 
       <Route path="*" component={Home} /> 
      </Router> 
     ) 
    } 
} 

,然後在主Index.js文件I想呈現如下:

import Routes from './components/Routes'; 

render((
    <div> 
     <div className="header">header</div> 
     <Routes /> 
    </div> 
), document.getElementById('app')); 

有人可以解釋我嗎?謝謝!

回答

18

從我的經驗,可以很好地定義佈局組件爲您的網頁,類似...

佈局組件

render() { 
    return(
     <div> 
      <Header /> 
      { this.props.children } 
      /* anything else you want to appear on every page that uses this layout */ 
      <Footer /> 
     </div> 
    ); 
} 

然後,您可以導入佈局,並將每個頁面組件的.. 。

聯繫頁面組件

render() { 
    return (
     <Layout> 
      <ContactComponent /> 
      /* put all you want on this page within the layout component */ 
     </Layout> 
    ); 
} 

和遊你可以保留你的路由相同,你的路由將呈現聯繫頁面,並反過來將呈現你的頭。

通過這種方式,您可以控制將在多個頁面上的重複內容,如果您需要一個或兩個略有不同的頁面,則可以創建另一個佈局並使用它。

+0

並且在主文件中我應該使用相同的結構進行路由,對嗎? – Hiero

+0

我認爲它不是更相關的做一個路線組件,並使它像這樣

+2

值得一提的是(使用React-Router作爲頁面上的組件,用你的'

'組件包裝它)。 –