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;
相关推荐
柯北(jvxiao)5 天前
Vue vs React 多维度剖析: 哪一个更适合大型项目?
前端·vue·react
袋鼠云数栈前端6 天前
扣子 Coze 产品体验功能
大数据·ai·react
想你依然心痛11 天前
React 表单处理:移动端输入场景下的卡顿问题与防抖优化方案
react
亦世凡华、16 天前
React--》实现 PDF 文件的预览操作
经验分享·pdf·react·pdf预览
技术路上的探险家17 天前
Web3:在 VSCode 中使用 Vue 前端与已部署的 Solidity 智能合约进行交互
vscode·web3·区块链·交互·react·solidity·ethers.js
友莘居士22 天前
Dify中的Agent和发现和调用mcp工具两个节点调用的异同
agent·react·dify·functioncalling·mcp
aiguangyuan23 天前
前端开发性能优化概要
系统架构·vue·react·前端开发
叶 落1 个月前
Component cannot be used as a JSX component
typescript·react
小浣熊喜欢揍臭臭1 个月前
react+antd+表格拖拽排序以及上移、下移、移到顶部、移到底部
前端·前端框架·react
小浣熊喜欢揍臭臭1 个月前
react+antd 可拖拽模态框组件
前端·javascript·react