如何在 React Router v4 中实现嵌套路由(子路由)?

How to implement nested Routing (child routes) in react router v4?

我想要的组件树如下 - 登录 - 家 - 接触 - 关于

Contact 和 About 是 Home 的子项。 这是我的 App.js ,

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>

          <Route exact path="/home" component={HomeView} />

        </div>
      </BrowserRouter>
    );
  }
}

render(<App />, document.getElementById('root'));

这是家,

export const HomeView = ({match}) => {
 return(
   <div>
    <NavBar />


    Here i want to render the contact component, (Navbar need to stay)

   </div>
 )

}

这是我的导航栏,

 export const NavBar = () => {
  return (
    <div>
      <Link to="/home">Home</Link> 
      <Link to="/home/contact">Contact</Link> 

      <hr/>
    </div>
  )
}

Contact 组件只需要渲染 "hello text".

要创建嵌套路由,您需要删除 exact:

<Route path="/home" component={HomeRouter} />

并添加一些路线:

export const HomeRouter = ({match}) => {
 return(
   <div>
    <NavBar />
    {/* match.path should be equal to '/home' */}
    <Switch>
      <Route exact path={match.path} component={HomeView} />
      <Route exact path={match.path + '/contact'} component={HomeContact} />
    <Switch>
   </div>
 )

}

您不需要在嵌套路由中使用 match.path,但如果您决定更改路由,这样可以更轻松地将所有内容从“/home”移动到“/new/home” .