【问题标题】:Is it possible to pass a value from child route to its parent route with react router?是否可以使用反应路由器将值从子路由传递到其父路由?
【发布时间】:2016-06-04 19:18:39
【问题描述】:

假设我有一个带有标题和正文的 MainLayout。使用 react 路由器,我在 body 中渲染组件。

...
<header></header>
<main>{this.props.children}</main>
...

这是我目前的路由器:

<Route component={MainLayout} onEnter={requireCordova}>
   <Route path="/home" component={Home} />
   <Route path="/settings" component={Settings} />
</Route>

我的问题是我希望 MainLayout 从它的一个子项中获取标题(以填充标题),这可能吗?

<Route component={MainLayout} onEnter={requireCordova}>
   <Route path="/home" component={Home} title='homepage' />
   <Route path="/settings" component={Settings} title='settings'  />
</Route>

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您不能直接在组件之间进行通信。您可能希望使用共享存储来满足此类要求 - 最流行的解决方案是 Redux

    为了解决您更新标题的具体问题 - 有一个简单的实用程序 react-helmet 可以简化流程。

    您可以在任何路由组件中简单地使用 Helmet 组件: &lt;Helmet title="My Title" /&gt; 和头盔将负责更新您的标题。它也适用于 HTML 头部中的其他元素 - 例如。元、链接、脚本标签等。

    【讨论】:

      猜你喜欢
      • 2016-12-08
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 2021-02-26
      • 2017-03-28
      • 2017-11-21
      • 2019-08-15
      • 2017-05-21
      相关资源
      最近更新 更多