如何在深度嵌套的React路由器对象中隐藏父级?

问题描述 投票:0回答:1

我想知道是否有更好的方法来隐藏/不渲染反应路由器对象中的父内容。我可以通过条件渲染来解决它,但我不确定这是最好的方法。我有父母、孩子和孙子,我将只渲染孙子内容,但保留嵌套结构(用于 useMatches 和其他内容)。我尝试使用 Outlet 但没有帮助。如何在 DOM 中隐藏父级和子级?

 const router: RouteObject = {
 id: "parent",
 path: "parent",
 element: <div><p>Parent</p></div>,

 children: [
   {
    id: "child",
    path: "/parent/child",
    element: <div><p>Child</p></div>,
  
     children: [
    {
      id: "grandchildLayout",
      index: true,
      element: <div><Outlet /></div>,
    },
    {
      id: "grandchild",
      path: "/parent/child/grandchild",
      element: <div><p>Grandchild</p></div>,
    },
  ],
},
],
};
javascript reactjs typescript react-router
1个回答
0
投票

Parent
Child
渲染为索引路线,以便它们仅在
"/parent"
"/parent/child"
上准确渲染。

示例:

const router: RouteObject = {
  id: "parent",
  path: "parent",
  children: [
    {
      index: true,
      element: (
        <div>
          <p>Parent</p>
        </div>
      )
    },
    {
      id: "child",
      path: "/parent/child",
      children: [
        {
          index: true,
          element: (
            <div>
              <p>Child</p>
            </div>
          )
        },
        {
          id: "grandchildLayout",
          element: (
            <div>
              <h3>Grandchild Layout</h3>
              <Outlet />
            </div>
          ),
          children: [
            {
              id: "grandchild",
              path: "/parent/child/grandchild",
              element: (
                <div>
                  <p>Grandchild</p>
                </div>
              )
            }
          ]
        }
      ]
    }
  ]
};

© www.soinside.com 2019 - 2024. All rights reserved.