【问题标题】:React router: route-based navbar contentReact 路由器:基于路由的导航栏内容
【发布时间】:2017-05-05 14:28:53
【问题描述】:

我有一个简单的单页 React 应用设置,带有导航栏、内容和页脚。导航栏本身由两个子导航栏组成:一个对每个页面都相同,另一个应该根据路由动态变化(特定于页面的导航栏)。

所以基本上,我有一个顶级组件Container

<Navbar>
  <Navbar.Main/>
  <Navbar.Page/>
</Navbar>
{this.props.children}
<Footer/>

以及App中定义的路由:

<Router history={browserHistory}>
  <Route component={Container}>
    <IndexRoute component={Home} />
    <Route path="/" component={Home} />
    <Route path="/contact" component={Contact} />
    <Route path="/about" component={About} />
    <Route path="*" component={NotFound} />
  </Route>
</Router>

虽然页面内容会在 {this.props.children} 部分内发生变化,但我想根据路由更改 &lt;Navbar.Page/&gt; 导航栏组件的内容(联系人页面应该具有特定于联系人的导航栏等)。

我知道我可以通过在页面内渲染页面导航栏轻松实现这一点,但我想继续在导航栏中进行渲染。

【问题讨论】:

标签: reactjs components react-router


【解决方案1】:

我们目前在项目中使用的一种方法是将组件道具传递给 Route 组件并做你想做的事情。

<Router history={browserHistory}>
  <Route component={Container}>
    <IndexRoute component={Home} />
    <Route path="/" component={Home} 
       // here I added components, but the name can be anything actually
       components={{ navBarPage : SomeComponent }} 
       navBarPages={{ component : SomeComponent }}
    />
    <Route path="/contact" component={Contact} />
    <Route path="/about" component={About} />
    <Route path="*" component={NotFound} />
  </Route>
</Router>

所以首先我们知道我们可以将 props 传递给路由,但另一件事是如何从组件中获取这些 props。

您可以放置​​一个调试器并在父 Container 组件中搜索您的 props,您可以看到您的 Container 组件有一个“路由”属性(又名 this.props.routes)。

但这是肮脏的事情,你必须知道组件相对于父路由器(又名组件 Container )有多深,这样你才能到达它。

例如调试您的 Container 组件以查看可用的道具:

当我添加组件 navBarPages 时,我可以从 Container 中访问这些对象:

this.props.routes[0] // this is what you passed to Container

this.props.routes[1] // one level deeper is what I want 
this.props.routes[1]['navBarPage']
this.props.routes[1]['components']

请注意,当然,随着您的路线更改,您的 this.props.routes 也会发生变化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 2020-10-27
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    相关资源
    最近更新 更多