【问题标题】:React-router-dom: How to update the props on a wrapper component?React-router-dom:如何更新包装组件上的道具?
【发布时间】:2020-03-28 00:16:29
【问题描述】:

我的 App 组件是这样的:

const App = (props) => (
  <BrowserRouter>
    <PageTheme {...some props I'd like to change on route change}>
      <Switch>
        <Route exact path="/example">
          <Example {...props} />
        </Route>
        <Route exact path="/example/detail/:exampleId">
          <ExampleDetail {...props} />
        </Route>
      </Switch>
    </PageTheme>
  </BrowserRouter>
);

包裹SwitchPageTheme 组件有一些导航UI,以及一些关于页面背景颜色等的选项。有没有办法为PageTheme 提供每条路线的一些特定道具?或者是在每个Route 中放置一个新的PageTheme 组件的最佳选择?谢谢!

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    你可以做的是使用withRouter并用它包裹PageTheme

    export default withRouter(PageTheme);
    

    如果PageTheme 是函数组件,则使用useLocation 钩子。比您可以访问location 并根据当前路由/url 施展魔法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多