首页 > 解决方案 > 访问匹配的子路由自定义道具(React Router v5)

问题描述

如何从 React 中的父组件访问匹配的路由自定义道具?

也就是说,拥有这样的路由器(react-router-config风格):

{
    component: App,
    routes: [
      {
        path: '/',
        exact: true,
        component: Home,
      },
      {
        path: '/account/',
        component: Account,
        headerOpened: true,
        routes: [
          {
            path: '/account/mi-cuenta/',
            exact: true,
            component: MyAccount,
          },
          {
            path: '/account/preferencias/',
            exact: true,
            component: Settings,
          },
          {
            path: '/account/mi-consumo/',
            exact: true,
            component: MyConsumption,
          },
        ],
      },
      { component: NotFound },
    ],
  }

如何从我的App组件访问headerOpened传递给的自定义道具Account

使用withRouterHOC in App,我无法在 match 或 location 对象中找到任何内容。我唯一拥有的是 location.pathname ,例如,显示/account/mi-cuenta/.

然后,我有匹配对象,其中仅包含参数(在这种情况下为空),但没有headerOpened道具的迹象。

从父组件获取此属性的原因是,此属性是组件的渲染器,Header现在需要该值。

在这里,一个小片段的App组件可能看起来像:

return (
        <div>
          <Header opened={ ??? }/>
          {renderRoutes(route.routes)}
          <Footer />
        <div/>
    );

标签: javascriptreactjsreact-routerreact-router-v4

解决方案


推荐阅读