【问题标题】:How to implement nested Routing (child routes) in react router v4?如何在反应路由器 v4 中实现嵌套路由(子路由)?
【发布时间】:2019-03-19 10:28:42
【问题描述】:

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

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”。

【问题讨论】:

    标签: reactjs routing nested react-router-v4


    【解决方案1】:

    要创建嵌套路由,您需要删除 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”,以防您决定更改路由。

    【讨论】:

    • 另外,你能告诉我们如何在有状态组件中使用 {match} 吗?
    猜你喜欢
    • 2017-05-19
    • 2019-01-12
    • 2019-02-18
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2018-01-26
    相关资源
    最近更新 更多