我正试着用React Router v4渲染多个布局.
例如,我想要具有以下路径的页面具有布局1:
> exact path =“/”
> path =“/ blog”
> path =“/ about”
> path =“/ projects”
以及具有布局2的以下路径:
> path =“/ blog /:id
> path =“/ project /:id
有效地回答了这里的问题,但是对于v4:Using multiple layouts for react-router components
其他答案都没有用,所以我提出了以下解决方案.我使用了
原文链接:https://www.f2er.com/react/300811.htmlrender
道具而不是最高级别的传统组件道具.
它使用layoutPicker函数根据路径确定布局.如果该路径未分配给布局,则返回“错误路由”消息.
import SimpleLayout from './layouts/simple-layout'; import FullLayout from './layouts/full-layout'; var layoutAssignments = { '/': FullLayout,'/pricing': FullLayout,'/signup': SimpleLayout,'/login': SimpleLayout } var layoutPicker = function(props){ var Layout = layoutAssignments[props.location.pathname]; return Layout ? <Layout/> : <pre>bad route</pre>; }; class Main extends React.Component { render(){ return ( <Router> <Route path="*" render={layoutPicker}/> </Router> ); } }
simple-layout.js和full-layout.js遵循以下格式:
class SimpleLayout extends React.Component { render(){ return ( <div> <Route path="/signup" component={SignupPage}/> <Route path="/login" component={LoginPage}/> </div> ); } }