加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React Router v4具有多种布局

发布时间:2020-12-15 20:55:13 所属栏目:百科 来源:网络整理
导读:我想在我的公共布局中渲染我的一些路线,以及我的私人布局中的其他一些路线,是否有一个干净的方法来做到这一点? 示例显然不起作用,但我希望大致解释我正在寻找的内容: Router PublicLayout Switch Route exact path="/" component={HomePage} / Route exact
我想在我的公共布局中渲染我的一些路线,以及我的私人布局中的其他一些路线,是否有一个干净的方法来做到这一点?

示例显然不起作用,但我希望大致解释我正在寻找的内容:

<Router>

  <PublicLayout>
    <Switch>
      <Route exact path="/" component={HomePage} />
      <Route exact path="/about" component={AboutPage} />
    </Switch>
  </PublicLayout>

  <PrivateLayout>
    <Switch>
      <Route exact path="/profile" component={ProfilePage} />
      <Route exact path="/dashboard" component={DashboardPage} />
    </Switch>
  </PrivateLayout>

</Router>

我想要切换某些路由的布局,如何使用新的路由器做到这一点?

嵌套路由不再有效,并给我这个错误:

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

编辑:布局包裹整组路线也意味着只要您保留在同一个私人/公共路线组中,这些布局只会呈现一次.如果您的布局必须从您的服务器获取某些东西,这是一个大问题,因为如果您使用布局包装每个页面,这将发生在每个页面更改上.

我为此做的是创建一个简单的组件,为Route组件添加一个额外的属性,即布局:
function RouteWithLayout({layout,component,...rest}){
  return (
    <Route {...rest} render={(props) =>
      React.createElement( layout,props,React.createElement(component,props))
    }/>
  );
}

然后在你的情况下你的路线将是这样的

<Switch>
    <RouteWithLayout layout={PublicLayout} path="/" component={HomePage}/>
    <RouteWithLayout layout={PublicLayout} path="/about" component={AboutPage}/>
    <RouteWithLayout layout={PrivateLayout} path="/profile" component={ProfilePage}/>
    <RouteWithLayout layout={PrivateLayout} path="/dashboard" component={DashboardPage}/>
</Switch>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读