react-route-dom 实现简单的嵌套路由

最终效果

点击 to test1

点击to test2 => to test21

点击to test2 => to test22

代码如下

javascript 复制代码
          path: "page",
          element: <父组件 />,
          children: [
            { path: "test1", element: <Test1 /> },
            {
              path: "test2",
              element: <Test2 />,
              children: [
                { path: "test21", element: <Test21 /> },
                { path: "test22", element: <Test22 /> },
              ],
            },
          ],

父组件如下

javascript 复制代码
   import { NavLink, Outlet } from "react-router-dom";    

         <div>
          I am 父组件
          <div>
            <NavLink to="/en/page/test1"> to test1</NavLink>
          </div>
          <div>
            <NavLink to="/en/page/test2"> to test2</NavLink>
          </div>
          <div style={{ marginLeft: "80px" }}>
            <Outlet />
          </div>
        </div>

test1组件

javascript 复制代码
import React from "react";
const Test1 = () => {
  return <div> I am test1</div>;
};
export default Test1;

test2组件

javascript 复制代码
import React from "react";
import { NavLink, Outlet } from "react-router-dom";

const Test2 = () => {
  return (
    <div>
      I am test2
      {/* link */}
      <div>
        <NavLink to="/en/apply/test2/test21"> to test21</NavLink>
      </div>
      <div>
        <NavLink to="/en/apply/test2/test22"> to test22</NavLink>
      </div>
      <div style={{ marginTop: "60px" }}>
        <Outlet />
      </div>
    </div>
  );
};
export default Test2;

test21组件

​​​​​​​

javascript 复制代码
import React from "react";
const Test21 = () => {
  return <div> I am test21</div>;
};
export default Test21;

test22组件

javascript 复制代码
import React from "react";
const Test22 = () => {
  return <div> I am test22</div>;
};
export default Test22;
相关推荐
2601_9679873715 小时前
Next.js 全栈开发入门指南(2026 最新版)
react·next.js·全栈开发·企业级开发·渲染模式
2601_967987371 天前
完整教程:Next.js项目演示(从零创建Next.js项目)Next.js入门实战
react·教程·前端开发·next.js·项目创建
goehou2 天前
ReAct 循环跑偏的三种样子,以及怎么在工程上兜住
llm·agent·react·工具调用·工程实践
大连好光景3 天前
ClaudeCode有关Agent Loop知识点大全
react·max_turns·agentloop·checkpoint快照·流式输入
汤米粥3 天前
2026年主流前端技术框架
vue·react·elementplus·tailwind css·angular‌·svelte‌·bootstrap‌
2601_967987374 天前
Next.js 文档
react·开发·全栈·文档·next.js
前进的李工4 天前
Agent 学习笔记 01:从工具调用到 ReAct 循环
笔记·学习·llm·agent·react·工具调用
Oiiouui5 天前
关于 Logto 登录系统的体验以及建议
javascript·安全·react
ZoeLandia5 天前
React11:数据请求与 TanStack Query
前端·react.js·typescript·react
漫步的猪7 天前
# 告别混乱与付费墙!Linkit:完全免费、本地优先的开源 AI 智能书签与收藏夹管理神器
人工智能·ai·开源·react·免费·书签·收藏夹