使用react-router将路由指向特定组件

时间:2016-03-09 18:40:20

标签: reactjs react-router

我想使用以下布局作为我的页面的开始屏幕:

-----------------------------
| View 1      | View 2      |
| LinkA LinkB | LinkC LinkD |
|             |             |
-----------------------------

点击LinkA or B后,我希望路线显示在View 1中, 当点击LinkC或D时,我希望路由显示在View 2

我现在所拥有的只是一种向App组件发送多个组件以呈现View1和View2的方法,我不知道如何在其中实际呈现特定路由:

  <Route path="/" component={ App }>
    <IndexRoute components={{
        view1: View1,
        view2: View2
      }} />
  </Route>

我对react-router的了解让我觉得我想要更多的东西:

  <Route path="/" component={ App }>
    <Route component={View1} >
      <Route to="linkA" component={View1a}/>
      <Route to="linkB" component={View1b}/>
    <Route />
    <Route component={View2} >
      <Route to="linkC" component={View2a}/>
      <Route to="linkD" component={View2b}/>
    <Route />
  </Route>

现在我的问题是如何使渲染按我的意愿工作,是否有任何教程显示这个? 也许我错过了一些基本的东西,因为我还没有找到这样的例子和我认为是页面的基本布局......

1 个答案:

答案 0 :(得分:1)

react-router配置的唯一问题是根据当前url确定要填充this.props.children的组件。您没有指定配置中显示的链接..您在组件中执行此操作。

在您的问题中,您说您希望开始屏幕包含两个视图。也许你的意思是两个组件?每个URL都负责一个视图。

配置如下:

<Route path="/" component={ App }>
  <Route path="view1" component={ View1 }>
    <Route path="a" component={ View1a } />
  <Route>
  <Route path="view2" component={ View2 } />
</Route>

当网址为/时,App组件的this.props.children将为空。如果您使用IndexRoute,它将使用那里指定的组件。

当网址为/view1时,App组件的this.props.children将呈现View1组件。 /view2View2也是如此。

当网址为/view1/a时,App组件的this.props.children将为View1,而View1的{​​{1}}将为this.props.children 1}}

因此,如果您想根据当前视图显示不同的链接,请在View1aView1组件中使用不同的链接。