使用React Router v4的多个布局

red*_*api 8 reactjs react-router react-router-v4

我正试着用React Router v4渲染多个布局.

例如,我想要具有以下路径的页面具有布局1:

  • 确切的路径="/"
  • PATH = "/博客"
  • 路径="/大约"
  • 路径="/项目"

以及具有布局2的以下路径:

  • PATH ="/博客/:ID
  • PATH ="/项目/:ID

有效地回答了这里的问题,但对于第4版:为反应路由器组件使用多个布局

spe*_*.sm 10

其他答案都没有用,所以我提出了以下解决方案.我使用了render道具而不是component最高级别的传统道具.

它使用该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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


simple-layout.jsfull-layout.js遵循以下格式:

class SimpleLayout extends React.Component {
  render(){
    return (
      <div>
        <Route path="/signup" component={SignupPage}/>
        <Route path="/login" component={LoginPage}/>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

所以,为此你应该使用渲染功能(https://reacttraining.com/react-router/core/api/Route/render-func)

一篇非常好的文章帮助了我:https://simonsmith.io/reusing-layouts-in-react-router-4/

最后你将使用这样的东西:

<Router>
 <div>
  <DefaultLayout path="/" component={SomeComponent} />
  <PostLayout path="/posts/:post" component={PostComponent} />
 </div>
</Router>
Run Code Online (Sandbox Code Playgroud)