【问题标题】:nested routes with common layout by react router 4react router 4 具有通用布局的嵌套路由
【发布时间】:2018-01-11 05:07:31
【问题描述】:

我现在正在将我的项目从 react-router 3.0.0 升级到 4.1.2,现在遇到了嵌套路由问题。

我想获得一个带有左侧菜单的侧边栏的页面,顶部的标题和右下角是主要内容部分。 从这里学习:Nested Routes in v4,我的代码是这样的:

<Router>
  <AppLayout>
    <Route path='/abc' component={ABC} />
    <Route path='/xyz' component={XYZ} />
  </AppLayout>
</Router>

其中组件AppLayout是一个常见的布局包含

        <Layout>
            <AppHeader/>
            <Layout>
                <Sider></Sider>
                <Layout>
                    <Content>
                        <div>{this.props.children}</div>
                    </Content>
                </Layout>
            </Layout>
            <Footer></Footer>
        </Layout>

AppLayout的内容是可以改变的,侧边栏的菜单需要和路由url紧密相关。所以我的问题是,如何从Router获取路由路径并将这些值设置到AppLayout中,以便可以选择菜单项以及路由更改。

【问题讨论】:

    标签: react-router-v4


    【解决方案1】:

    您可以为此使用上下文。

    在您的appLayout 组件中:

    class AppLayout extends Component {
    static contextTypes = {
         router: PropTypes.object
    }
    render (){
       // your code here.
    }
    

    您可以从const { url } = this.context.router.route.match获取网址。

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 1970-01-01
      • 2016-11-12
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      相关资源
      最近更新 更多