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;
相关推荐
程序员小续7 天前
React源码解读
前端·javascript·react.js·webpack·前端框架·node.js·react
飞奔的龟龟12 天前
getDerivedStateFromProps 详解
react
Liigo14 天前
初次体验Tauri和Sycamore (2)
rust·react·tauri·webassembly·jsx·sycamore·dioxus
Lysun0011 个月前
redux 结合 @reduxjs/toolkit 的使用
开发语言·前端·javascript·react·redux
远洋录1 个月前
支付宝八折事件启示录:用户体验与风险管理的平衡艺术
前端·人工智能·react
迪迦1 个月前
React实现拖拽特效
javascript·react
远洋录1 个月前
Electron 开发者的 Tauri 2.0 实战指南:文件系统操作
前端·人工智能·react
远洋录1 个月前
Electron 开发者的 Tauri 2.0 实战指南:安全实践
前端·人工智能·react
远洋录1 个月前
Vue 开发者的 React 实战指南:测试篇
前端·人工智能·react
远洋录1 个月前
Vue 开发者的 React 实战指南:表单处理篇
前端·人工智能·react