首页 > 解决方案 > 如何使嵌套的反应路由器组件加载到新页面而不是页面的一半

问题描述

我目前有一种情况,我的文件中有我的主要父路由/开关,App.js但在文件中的一个路由中App.js,我有另一个组件,它也有它自己<Router>的路由/开关设置,它调用另一个名为<MyJobComponent />

我设置的文件层次结构如下:

App.js - has route/path to the component <AllJobs />
  |
  |---> AllJobs.js - has nested route/path to the component <MyJobComponent />
           |
           |---> MyJobComponent.js - has the <Link to={`/my-job-id/${item.job_id}`}

在这里,这个组件在AllJobs.js关卡而不是在App.js关卡被渲染,这是我希望它被渲染的地方。

<Switch>
  <Route exact path="/job-path/:jobID" component={MyJobComponent} />
</Switch>

<MyJobComponent />我有以下Link to代码:

<TableCell style={{width: '10%'}}>
  <Link
     to={`/my-job-id/${item.job_id}`}
     style={{ textDecoration: 'underline', color: 'black' }}
  >             
    {item.job_id}
  </Link>
</TableCell> 

单击此按钮Link to会将我的页面呈现在页面的中间<MyJobComponent />

基于 react-router 嵌套示例更新

在此处查看此示例:React-Router Nested如果您单击Topics然后单击Components主题下的子链接,您将看到它components在这些子链接下方显示标题。

这是我想在它自己的页面上显示的子链接下方的这一部分,即components。这可能吗?

标签: javascriptreactjsreact-router-domreact-router-v4

解决方案


将此代码移至 App.js:

<Switch>
  <Route exact path="/job-path/:jobID" component={MyJobComponent} />
</Switch>

推荐阅读