2017-07-27 107 views
1

我正在使用React构建一个多页面应用程序。我有三个组件。 Header将出现在所有页面上,并且Page1Page2将作为不同的页面呈现在页眉下方。 Header看起来是这样的:React多页面路由

class Header extends React.Component { 
    return (
     <header component HTML code...> 
     {this.props.children} // this is where Page1 and Page2 will render 
           // depending on the URL 
    ); 
} 

我的路由器组成部分看起来像这样(我用的是react-router-dom包):

const routes = (
    <BrowserRouter> 
    <Switch> 
     <Route path="/" component={Header} /> 
     <Route path="/welcome" component={Page1} /> 
     <Route path="/default" component={Page2} /> 
    </Switch> 
    </BrowserRouter> 
); 

访问/呈现头部,但/welcome/default返回一个404。我试着这样做使用嵌套路由:

<BrowserRouter> 
    <Route component={Base}> 
     <Route path="/welcome" component={Page1}/> 
     <Route path="/landing" component={Page2}/> 
    </Route> 
</BrowserRouter> 

这给出了一个错误-

You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored 

有人可以指出我做得不对吗?有没有更好的方法来实现我想要的?

+1

都看看这个。 https://stackoverflow.com/questions/36262360/react-router-global-header – aravindaM

回答

0

试试这个:

const routes =() =>(
    <BrowserRouter> 
    <div> 
     <Header /> 
     <Route path='/welcome' exact component={Page1} /> 
     <Route path='/default' exact component={Page2} /> 
    </div> 
    </BrowserRouter> 
) 

,因为我们没有为Header指定任何Route,它会使得所有的时间,而不管路径