React Router - 为不相关的路由指定父组件 [英] React Router - Specify parent component for unrelated routes

查看:29
本文介绍了React Router - 为不相关的路由指定父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 React 应用中有 3 个页面以及以下路径:

  1. 登录 (/)
  2. 仪表板 (/dashboard)
  3. 项目 (/projects)

我希望仪表板和项目页面有标题,但登录页面不应该有任何标题.

目前的路线是这样的:

<路由器><Route path="/" component={Login}><Route path="/dashboard" component={Dashboard}/><Route path="/projects" component={Projects}/></路由器>

我创建了一个名为 Shell 的组件,它只提供标题.如何设置我的路由器,使 Shell 是 DashboardProjects 的父组件,而不是 Login 页面的父组件?

编辑 1

我想知道是否可以使用这样的无路径父级来围绕子组件渲染 Shell:

<路由器><Route path="/" component={Login}><路由组件={Shell}><Route path="/dashboard" component={Dashboard}/><Route path="/projects" component={Projects}/></路线></路由器>

编辑 2

刚刚尝试了上面的更改,它起作用了!阅读文档,path 不是必需的道具.所以在上面的代码中 是完全合法的.

解决方案

您在编辑 1 中的内容是正确的.

<路由器><路由组件={登录}><路由组件={Shell}><Route path="/dashboard" component={Dashboard}/><Route path="/projects" component={Projects}/></路线></路由器>

在你的 组件中,你可以:

import Header from './Header';...使成为() {返回 (<div id="shell"><标题/>{this.props.children}

);}...

I have 3 pages in my React App along with the following routes:

  1. Login (/)
  2. Dashboard (/dashboard)
  3. Projects (/projects)

I would like the Dashboard and Project pages to have a header, but the Login page should not have any header.

Currently the routes look like this:

<Router>
    <Route path="/" component={Login}>
    <Route path="/dashboard" component={Dashboard} />
    <Route path="/projects" component={Projects} />
</Router>

I have created a component called Shell which provides just the header. How do I setup my router so that Shell is parent component for Dashboard and Projects but not the Login page?

Edit 1

I am wondering if it is possible to use a pathless parent like this to render the Shell around the child components:

<Router>
    <Route path="/" component={Login}>
    <Route component={Shell}>
        <Route path="/dashboard" component={Dashboard} />
        <Route path="/projects" component={Projects} />
    </Route>
</Router>

Edit 2

Just tried the change above and it works! Reading the docs, path is not a required prop. So in the code above <Route component={Shell}> is perfectly legit.

解决方案

What you have in Edit 1 is correct.

<Router>
  <Route component={Login}>
  <Route component={Shell}>
    <Route path="/dashboard" component={Dashboard} />
    <Route path="/projects" component={Projects} />
  </Route>
</Router>

And in your <Shell> component, you can do:

import Header from './Header';

...

render() {
  return (
    <div id="shell">
      <Header />
      {this.props.children}
    </div>
  );
}
...

这篇关于React Router - 为不相关的路由指定父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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