React Router v4 的多种布局 [英] Multiple Layouts with React Router v4

查看:42
本文介绍了React Router v4 的多种布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力尝试使用 React Router v4 渲染多个布局.

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

  • 确切路径="/"
  • path="/blog"
  • path="/about"
  • path="/projects"

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

  • path="/blog/:id
  • path="/project/:id

除了 v4 之外,这里有效地回答了什么:使用多种布局进行反应-路由器组件

解决方案

其他答案都不起作用,所以我想出了以下解决方案.我使用了 render prop 而不是传统的 component prop 在最高级别.

它使用 layoutPicker 函数根据路径确定布局.如果该路径未分配给布局,则会返回错误路径"消息.

import SimpleLayout from './layouts/simple-layout';从 './layouts/full-layout' 导入 FullLayout;var layoutAssignments = {'/':全布局,/定价":全版式,/注册":简单布局,/登录":简单布局}var layoutPicker = 函数(道具){var Layout = layoutAssignments[props.location.pathname];返回布局?<布局/>:<pre>坏路由</pre>;};class Main 扩展了 React.Component {使成为(){返回 (<路由器><Route path="*" render={layoutPicker}/></路由器>);}}


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

class SimpleLayout 扩展 React.Component {使成为(){返回 (<div><Route path="/signup" component={SignupPage}/><Route path="/login" component={LoginPage}/>

);}}

I'm pulling my hair out trying to render multiple layouts with React Router v4.

For instance, I'd like pages with the following paths to have layout 1:

  • exact path="/"
  • path="/blog"
  • path="/about"
  • path="/projects"

and the following paths to have layout 2:

  • path="/blog/:id
  • path="/project/:id

Effectively what's being answered here but for v4: Using multiple layouts for react-router components

解决方案

None of the other answers worked so I came up with the following solution. I used the render prop instead of the traditional component prop at the highest level.

It uses the layoutPicker function to determine the layout based on the path. If that path isn't assigned to a layout then it returns a "bad route" message.

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 and full-layout.js follow this format:

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

这篇关于React Router v4 的多种布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆