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;
相关推荐
祖国的好青年2 小时前
Prettier实现保存自动格式化
vscode·react·prettier
Tbisnic5 小时前
AI大模型学习 第十天:让程序“指挥”大模型 —— 从对话到工具调用
人工智能·python·ai·大模型·react·cot·提示词工程
蜂蜜黄油呀土豆7 小时前
Agent 循环:观察、思考、行动(ReAct 入门)
python·ai·大模型·react·js
英俊潇洒美少年1 天前
React18 flushSync 完整深度解析
前端·react
小牛itbull2 天前
告别传统主题开发!ReactPress Theme Starter —— 用 Next.js 15 构建现代化无头博客
javascript·cms·react·wordpress·nextjs·reactpress·blog-theme
李燚4 天前
Eino 的 ReAct 循环是怎么跑起来的:图、节点、分支
golang·agent·react·ai-agent
小书房4 天前
移动开发跨平台方案之RN/Flutter/KMP/CMP
flutter·react native·react·跨平台·rn·kmp·cmp
逻极4 天前
Hermes Agent深度解析:从ReAct到多智能体系统架构实战
llm·agent·react·rag·多智能体系统
2501_912784085 天前
跨境自建站踩坑总结:放弃开源商城二开,改用成熟 Taocarts SaaS 落地跨境项目
react·taocarts·跨境saas
Artech6 天前
[MAF预定义ChatClient中间件-02]FunctionInvokingChatClient——实现ReAct循环和人机交互的大功臣
ai·agent·react·maf·ichatclient