跳到正文
灵动桌面框架
Esc
本栏目菜单

路由和导航

灵动桌面框架使用 React Router 7(react-router-dom ^7.13.1)管理页面路由,桌面端采用 Data Router 写法:createBrowserRouter + RouterProvider。

路由配置

// src/Router.tsx
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { AppLayout } from "@/components/layout/AppLayout";
import HomePage from "@/pages/home";
import SettingsPage from "@/pages/settings";
import AboutPage from "@/pages/about";

const router = createBrowserRouter([
  {
    path: "/",
    element: <AppLayout />,
    children: [
      { index: true, element: <HomePage /> },
      { path: "settings", element: <SettingsPage /> },
      { path: "about", element: <AboutPage /> },
    ],
  },
]);

export function AppRouter() {
  return <RouterProvider router={router} />;
}

App.tsx 中以 <AppRouter /> 挂载路由。所有页面都是 AppLayout 的子路由,通过布局里的 <Outlet /> 渲染到内容区。

路径页面说明
/src/pages/home首页(index 路由),Greet 示例
/settingssrc/pages/settings设置:检查更新 + SQLite 配置列表
/aboutsrc/pages/about关于:系统信息 + 技术栈

桌面端与移动端的路由方式不同

桌面端页面由 Tauri 的自定义协议加载(不是 file://),History API 可以正常使用,所以 src/Router.tsx 用的是 createBrowserRouter。

移动端独立 SPA(src/mobile/MobileApp.tsx)用的是 HashRouter,因为它要同时兼容 Tauri Mobile 和远程网关的任意子路径托管。

侧边栏导航

// src/components/layout/Sidebar.tsx(节选,省略了标题区的内联样式)
import { useNavigate, useLocation } from "react-router-dom";
import { Menu } from "antd";
import { Home, Info } from "lucide-react";
import { useAppStore } from "@/store";

const menuItems = [
  { key: "/", icon: <Home size={18} />, label: "首页" },
  { key: "/about", icon: <Info size={18} />, label: "关于" },
];

export function Sidebar() {
  const navigate = useNavigate();
  const location = useLocation();
  const collapsed = useAppStore((s) => s.sidebarCollapsed);

  return (
    <div className="flex flex-col h-full">
      <div className="h-12 flex items-center justify-center font-bold text-base">
        {collapsed ? "AT" : "Agile Tauri"}
      </div>
      <Menu
        mode="inline"
        selectedKeys={[location.pathname]}
        items={menuItems}
        onClick={({ key }) => navigate(key)}
        style={{ border: "none", flex: 1 }}
      />
    </div>
  );
}

菜单项的 key 就是完整路径,selectedKeys 直接取 location.pathname 实现高亮。侧边栏里只有「首页」和「关于」,「设置」页的入口是顶栏右侧的齿轮按钮(AppLayout 中 navigate("/settings"))。

添加新页面

  1. 创建页面组件 src/pages/my-page/index.tsx(默认导出)
  2. 在 Router.tsx 的 children 中添加路由
  3. 在 Sidebar.tsx 的 menuItems 中添加菜单项
// 1. 页面组件
export default function MyPage() {
  return <div className="max-w-2xl mx-auto">新页面</div>
}

// 2. 路由(Router.tsx 的 children 数组,path 不带开头的 /)
{ path: "my-page", element: <MyPage /> },

// 3. 菜单项(key 写完整路径,与 location.pathname 对应)
{ key: "/my-page", icon: <Star size={18} />, label: "新页面" },