首页
赞助博主
友链
关于
工具
推荐
我的B站主页
我的歌单
我的bgm
井字棋
待办事项
随机cg
github加速
Search
1
iOS永久不续签随意装软件,trollstore巨魔商店安装教程
3,419 阅读
2
进入自己原神服务器
1,747 阅读
3
linux云服开原神服务器
1,604 阅读
4
从零开始的mc联机教程
1,116 阅读
5
win上开原神服务器
1,107 阅读
默认分类
原神
MC
iOS
galgame
ReinaManager
学习笔记
开发笔记
登录
Search
标签搜索
原神
私服
win
reinamanager
安卓
rust
tauri
react
seaorm
mui
react router
tauri-plugin-sql
migration
sea-orm-cli
基线迁移
数据库迁移
火神80
累计撰写
12
篇文章
累计收到
14
条评论
首页
栏目
默认分类
原神
MC
iOS
galgame
ReinaManager
学习笔记
开发笔记
页面
赞助博主
友链
关于
工具
推荐
我的B站主页
我的歌单
我的bgm
井字棋
待办事项
随机cg
github加速
搜索到
2
篇与
的结果
2025-10-04
seaorm迁移初体验——从tauri-plugin-sql重构到seaorm #1 数据库迁移脚本
前言随着reinamanager的逐步开发,我发现games表实在太臃肿了,为了以后能更好的,添加新的数据源、交叉显示游戏数据、发挥各数据源的特性等,于是我决定把games表拆分成多个表;由于项目初期使用了tauri-plugin-sql插件,games表拆分后会导致repository层多个game数据表的交互逻辑变得异常复杂,换言之就是sql语句会变得很复杂。再加上之前有人建议我使用orm代替纯sql查询issue。那就来吧!要说rust家族里的orm,那肯定首推seaorm。追平与基线迁移原来使用的是tauri-plugin-sql,想彻底重构到seaorm得做基线迁移,在基线迁移脚本中判断用户类型,新用户运行数据库初始化函数,创建全新的数据库结构,老用户先运行旧的迁移脚本(追平),然后将旧的迁移表_sqlx_migrations备份一份,以完成基线迁移。使用sea-orm-migration来创建一个迁移crate:cargo install sea-orm-cli sea-orm-cli migrate init sea-orm-cli migrate generate xxx因为旧的迁移脚本是基于sqlx的,还有数据库放在AppData下,所以为migration crate添加sqlx、dirs-next、url等依赖:[dependencies] sqlx = { version = "0.8", features = [ "sqlite", "runtime-tokio-native-tls", "migrate", ] } dirs-next = "2" url = "2"基线迁移脚本:use sea_orm::{ConnectionTrait, DatabaseBackend, Statement}; use sea_orm_migration::prelude::*; use sea_orm_migration::sea_orm::TransactionTrait; # [derive(DeriveMigrationName)] pub struct Migration; # [async_trait::async_trait] impl MigrationTrait for Migration { async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { let conn = manager.get_connection(); // 开启事务,保证所有操作的原子性 let txn = conn.begin().await?; // 判断是否为新用户 - 检查是否存在任何遗留数据表 let is_new_user = !has_any_legacy_tables(&txn).await?; if is_new_user { println!("[MIGRATION] New user detected, creating modern split table structure"); create_modern_schema(&txn).await?; } else { println!("[MIGRATION] Existing user detected, running legacy migration catch-up"); run_legacy_migrations_with_sqlx().await?; } // 提交事务 txn.commit().await?; println!("[MIGRATION] v1 baseline schema created successfully"); Ok(()) } } /// 检查是否存在任何遗留数据表或数据 async fn has_any_legacy_tables<C>(conn: &C) -> Result<bool, DbErr> where C: ConnectionTrait, { // 检查是否存在 tauri-plugin-sql 的迁移表 let legacy_migration_exists = conn .query_one(Statement::from_string( DatabaseBackend::Sqlite, "SELECT 1 FROM sqlite_master WHERE type='table' AND name='_sqlx_migrations'", )) .await? .is_some(); Ok(legacy_migration_exists) } /// 为新用户创建现代的拆分表结构 async fn create_modern_schema<C>(conn: &C) -> Result<(), DbErr> where C: ConnectionTrait, { ...... // 5. 创建关联表 create_related_tables(conn).await?; // 6. 创建现代结构的索引 create_modern_indexes(conn).await?; Ok(()) } /// 创建关联表(游戏会话、统计、存档等) async fn create_related_tables<C>(conn: &C) -> Result<(), DbErr> where C: ConnectionTrait, { ...... Ok(()) } /// 为现代拆分结构创建索引 async fn create_modern_indexes<C>(conn: &C) -> Result<(), DbErr> where C: ConnectionTrait, { let indexes = [ // games 表索引 ...... ]; for (index_name, table_name, column_name) in &indexes { conn.execute(Statement::from_string( DatabaseBackend::Sqlite, format!( r#"CREATE INDEX IF NOT EXISTS "{}" ON "{}" ("{}")"#, index_name, table_name, column_name ), )) .await?; } Ok(()) } /// 为现有用户运行旧的 tauri-plugin-sql 迁移,使用 sqlx 执行 async fn run_legacy_migrations_with_sqlx() -> Result<(), DbErr> { println!("[MIGRATION] Running legacy migrations with sqlx..."); // 获取数据库连接 URL(从系统目录推导) let database_url = get_db_path()?; // 创建 sqlx 连接池 let pool = sqlx::SqlitePool::connect(&database_url) .await .map_err(|e| DbErr::Custom(format!("Failed to connect with sqlx: {}", e)))?; // 检查并运行旧迁移 run_legacy_migration_001(&pool).await?; run_legacy_migration_002(&pool).await?; // 清理 sqlx 的迁移记录,因为我们转移到 SeaORM cleanup_sqlx_migration_table(&pool).await?; pool.close().await; println!("[MIGRATION] Legacy migrations completed successfully"); Ok(()) } /// 从系统目录推导数据库连接字符串(无需外部参数) fn get_db_path() -> Result<String, DbErr> { use std::path::PathBuf; // 使用 config_dir (Roaming on Windows) 来匹配原先的 app_data_dir 行为 let base = dirs_next::config_dir() .or_else(dirs_next::data_dir) .ok_or_else(|| DbErr::Custom("Failed to resolve user data directory".to_string()))?; let db_path: PathBuf = base .join("com.reinamanager.dev") .join("data") .join("reina_manager.db"); // 使用 url::Url::from_file_path 保证路径格式正确 let db_url = url::Url::from_file_path(&db_path) .map_err(|_| DbErr::Custom("Invalid database path".to_string()))?; let conn = format!("sqlite:{}?mode=rwc", db_url.path()); Ok(conn) } /// 运行旧迁移 001 - 数据库初始化 async fn run_legacy_migration_001(pool: &sqlx::SqlitePool) -> Result<(), DbErr> { println!("[MIGRATION] Checking legacy migration 001..."); // 检查是否已经执行过这个迁移 let migration_exists = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM _sqlx_migrations WHERE version = 1") .fetch_one(pool) .await .unwrap_or(0) > 0; if migration_exists { println!("[MIGRATION] Migration 001 already applied, skipping"); return Ok(()); } println!("[MIGRATION] Applying migration 001 - database initialization"); // 执行迁移 001 的 SQL let migration_sql = include_str!("../old_migrations/001_database_initialization.sql"); sqlx::query(migration_sql) .execute(pool) .await .map_err(|e| DbErr::Custom(format!("Failed to execute migration 001: {}", e)))?; // 记录迁移 sqlx::query( "INSERT INTO _sqlx_migrations (version, description, installed_on, success, checksum, execution_time) VALUES (1, 'database_initialization', datetime('now'), 1, 0, 0)" ) .execute(pool) .await .map_err(|e| DbErr::Custom(format!("Failed to record migration 001: {}", e)))?; println!("[MIGRATION] Migration 001 applied successfully"); Ok(()) } /// 运行旧迁移 002 - 添加自定义字段 async fn run_legacy_migration_002(pool: &sqlx::SqlitePool) -> Result<(), DbErr> { println!("[MIGRATION] Checking legacy migration 002..."); // 检查是否已经执行过这个迁移 let migration_exists = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM _sqlx_migrations WHERE version = 2") .fetch_one(pool) .await .unwrap_or(0) > 0; if migration_exists { println!("[MIGRATION] Migration 002 already applied, skipping"); return Ok(()); } println!("[MIGRATION] Applying migration 002 - add custom fields"); // 执行迁移 002 的 SQL let migration_sql = include_str!("../old_migrations/002_add_custom_fields.sql"); sqlx::query(migration_sql) .execute(pool) .await .map_err(|e| DbErr::Custom(format!("Failed to execute migration 002: {}", e)))?; // 记录迁移 sqlx::query( "INSERT INTO _sqlx_migrations (version, description, installed_on, success, checksum, execution_time) VALUES (2, 'add_custom_fields', datetime('now'), 1, 0, 0)" ) .execute(pool) .await .map_err(|e| DbErr::Custom(format!("Failed to record migration 002: {}", e)))?; println!("[MIGRATION] Migration 002 applied successfully"); Ok(()) } /// 清理 sqlx 的迁移记录表,为转移到 SeaORM 做准备 async fn cleanup_sqlx_migration_table(pool: &sqlx::SqlitePool) -> Result<(), DbErr> { println!("[MIGRATION] Cleaning up sqlx migration records..."); // 可选:保留迁移历史但重命名表 sqlx::query("ALTER TABLE _sqlx_migrations RENAME TO _legacy_sqlx_migrations") .execute(pool) .await .map_err(|e| DbErr::Custom(format!("Failed to rename sqlx migrations table: {}", e)))?; println!("[MIGRATION] sqlx migration table renamed to _legacy_sqlx_migrations"); Ok(()) }games表拆分先关闭外键约束,再创建新的核心games表,创建各个数据源的数据表,以及一个other_data表用于存放一些通用数据,其次用旧的games表数据填充新的数据表,然后备份、删除并重建受外键影响的表,再然后删除原games表并重命名新表,最后重新开启外键约束,重建数据库以回收空间并整理碎片。games表拆分脚本:use sea_orm::{ConnectionTrait, DatabaseBackend, Statement}; use sea_orm_migration::prelude::*; use sea_orm_migration::sea_orm::TransactionTrait; #[derive(DeriveMigrationName)] pub struct Migration; #[async_trait::async_trait] impl MigrationTrait for Migration { async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { // 检查是否已经拆分(通过检查 bgm_data 表是否存在) let already_split = manager.has_table("bgm_data").await?; if already_split { // 已经拆分过,直接返回 return Ok(()); } // 执行表拆分逻辑 split_games_table(manager).await?; Ok(()) } } async fn split_games_table(manager: &SchemaManager<'_>) -> Result<(), DbErr> { let conn = manager.get_connection(); // 0. 关闭外键约束 conn.execute(Statement::from_string( DatabaseBackend::Sqlite, "PRAGMA foreign_keys = OFF;", )) .await?; // 开启事务,保证所有操作的原子性 let txn = conn.begin().await?; // 1. 创建新的核心 games 表(只保留本地管理相关字段) // 2. 创建 BGM 数据表 // 3. 创建 VNDB 数据表 // 4. 创建其他数据表 // 5. 迁移数据从原 games 表到新表结构 // 5.1 迁移核心 games 数据 // 5.2 迁移 BGM 相关数据 // 5.3 迁移 VNDB 相关数据 // 5.4 迁移其他数据(custom, Whitecloud 等) // 6. 备份、删除并重建受外键影响的表 // 6.1 处理 game_sessions 表 // 6.2 处理 game_statistics 表 // 6.3 处理 savedata 表 // 7. 删除原 games 表并重命名新表 // 8. 提交事务 txn.commit().await?; // 9. 重新开启外键约束 conn.execute(Statement::from_string( DatabaseBackend::Sqlite, "PRAGMA foreign_keys = ON;", )) .await?; // 10. (推荐) 重建数据库以回收空间并整理碎片 conn.execute_unprepared("VACUUM;").await?; Ok(()) }相比tauri-plugin-sql的sql式迁移脚本,seaorm的rust迁移脚本可太好用了好吧。迁移代码详情见migration
2025年10月04日
8 阅读
0 评论
1 点赞
2025-09-14
在 MUI Toolpad Core(仪表盘布局) + React Router 项目中实现滚动条的保存与恢复
放一只无人认领的希亚(x省流点我跳到原因与解决方案引言:一个“简单”的需求在我开发 ReinaManager 的过程中,我有一个简单的需求:在不同路由页面间切换时,能够保存并恢复页面的滚动条位置。比如:当我在游戏库向下滑动了一段距离,点击进入某个游戏的详情页,然后再返回游戏仓库时,我希望它能回到之前浏览的位置,而不是页面的最顶端。这听起来很简单,对吧?我一开始也这么认为。然而,就是这个看似“简单”的需求,将我拖入了一场长达数天的、与 MUI Toolpad Core 中仪表盘布局(Dashboard Layout)、React Router 和各种状态管理库之间的战斗...第一阶段:天真的尝试 —— KeepAlive 与 Router 的 <ScrollRestoration />1. “釜底抽薪”:组件保活(react-activation)我的第一个想法是:如果页面不被卸载,那滚动条位置不就自然保存下来了吗?于是我引入了 react-activation 库。实际上,react-activation 的组件保活不包括滚动条位置的保存,它提供了一个 saveScrollPosition 属性:2. “官方正统”<ScrollRestoration />React Router v6.4+ 官方提供了一个保存滚动条的解决方案:<ScrollRestoration /> 组件。文档说明,只需要在应用中渲染它,就能自动处理滚动恢复。小结在我的项目中,这两种方法都没能奏效,于是就这样进入了第二阶段...第二阶段:原因的探索 —— 为什么这些方法都不奏效?既然别人造的轮子都没用,那就自己动手搓一个,可是要想自己造轮子,首先得弄清楚为什么这些轮子在我的项目中不适用,不弄清楚这个“为什么”,自定义的方案也无从下手。经过文档翻阅、devtools 调试、排除法(最笨但是很有效 x)等手段,我终于发现了问题的根源:Toolpad Core 仪表盘布局(Dashboard Layout)渲染的滚动容器并不是整个 window,而是在一个 main 标签内,这个 main 标签是由 DashboardLayout 组件渲染的。仪表盘布局结构如下:DashboardLayout (渲染滚动容器 main) └── <Outlet /> (渲染各个页面组件)对于 KeepAlive:它只检测 KeepAlive 子组件中的可滚动元素。如果放在 DashboardLayout 外层,因为路由的切换,Outlet 部分会变化,导致子组件无法缓存,切换路由会让子组件重新渲染(我不是为了保活组件才加 react-activation 这个库的么?)。如果放在子组件外层,如包裹 Library 组件,滚动容器又不是在子组件内,saveScrollPosition 属性就无效了。对于 <ScrollRestoration />:它期望滚动发生在 window 或 document 上。位于 main 标签内的滚动容器不在它的监控范围内,因此它无法正确监听到不同子组件的滚动事件,也就无法保存和恢复滚动位置。第三阶段:自定义方案 —— 自己动手,丰衣足食既然知道了滚动容器是 main 标签,那我就有了这样的想法:在路由切换之前保存滚动条位置,组件加载时用自定义 hook 恢复滚动条。1. 保存滚动位置scrollStore.ts// src/store/scrollStore.ts // 使用 zustand 创建一个简单的全局状态管理,用于保存各个路径的滚动位置 import { create } from 'zustand'; interface ScrollState { scrollPositions: Record<string, number>; setScrollPosition: (path: string, position: number) => void; } export const useScrollStore = create<ScrollState>((set) => ({ scrollPositions: {}, setScrollPosition: (path, position) => set((state) => ({ scrollPositions: { ...state.scrollPositions, [path]: position, }, })), }));scrollUtils.ts// 工具函数,用于保存滚动位置 // src/utils/scrollUtils.ts import { useScrollStore } from '@/store/scrollStore'; //保存指定路径的滚动条位置 export const saveScrollPosition = (path: string) => { const SCROLL_CONTAINER_SELECTOR = 'main'; const container = document.querySelector<HTMLElement>(SCROLL_CONTAINER_SELECTOR); // 增加一个检查,确保容器是可滚动的,避免无效保存 if (container && container.scrollHeight > container.clientHeight) { const scrollTop = container.scrollTop; useScrollStore.setState(state => ({ scrollPositions: { ...state.scrollPositions, [path]: scrollTop, } })); } };2. 恢复滚动位置(二编)useRestoreScroll.tsimport { useEffect, useRef, useCallback } from 'react'; import { useLocation } from 'react-router-dom'; import { useScrollStore } from '@/store/scrollStore'; import { useActivate, useUnactivate } from 'react-activation'; interface UseScrollRestoreOptions { /** 滚动容器选择器,默认 'main' */ containerSelector?: string; /** 是否正在加载中 */ isLoading?: boolean; /** 超时时间(ms),默认 2000 */ timeout?: number; /** 是否启用调试日志 */ debug?: boolean; /** 内容稳定检测的等待时间(ms),默认 150 */ stabilityDelay?: number; /** 是否在 KeepAlive 中使用 */ useKeepAlive?: boolean; } const DEFAULT_OPTIONS: Required<Omit<UseScrollRestoreOptions, 'isLoading'>> = { containerSelector: 'main', timeout: 1500, debug: false, stabilityDelay: 0, useKeepAlive: false, }; /** * 滚动位置还原 Hook (优化版) * * 特性: * - 智能检测内容是否渲染完成(高度稳定检测) * - 支持滚动到底部的场景 * - 避免滚动抖动和跳跃 * - 自动清理资源,防止内存泄漏 */ export function useScrollRestore( scrollPath: string, options: UseScrollRestoreOptions = {} ) { const { containerSelector, isLoading, timeout, debug, stabilityDelay, useKeepAlive } = { ...DEFAULT_OPTIONS, ...options, }; const location = useLocation(); const { scrollPositions } = useScrollStore(); const cleanupRef = useRef<(() => void) | null>(null); const settledRef = useRef(false); const lastPathRef = useRef<string>(''); const lastHeightRef = useRef(0); const stabilityTimerRef = useRef<number | null>(null); const log = useCallback( (...args: any[]) => { if (debug) console.log('[useScrollRestore]', ...args); }, [debug] ); useEffect(() => { if ('scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } }, []); // 提取滚动恢复逻辑为独立函数 const performScrollRestore = useCallback(() => { // 路径变化时重置状态 if (lastPathRef.current !== location.pathname) { settledRef.current = false; lastPathRef.current = location.pathname; lastHeightRef.current = 0; } // 清理上一次的副作用 if (cleanupRef.current) { log('Cleaning up previous effect'); cleanupRef.current(); cleanupRef.current = null; } if (isLoading) { log('Skipping: isLoading=true'); return; } const container = document.querySelector<HTMLElement>(containerSelector); if (!container) { log('Container not found:', containerSelector); return; } const isTargetPath = location.pathname === scrollPath; const target = isTargetPath ? (scrollPositions[scrollPath] || 0) : 0; log('Target position:', target, 'for path:', location.pathname); // 快速路径:目标为 0 if (target === 0) { container.scrollTop = 0; settledRef.current = true; log('Scrolled to top immediately'); return; } if (settledRef.current) { log('Already settled, skipping'); return; } let ro: ResizeObserver | null = null; let fallbackTimer: number | null = null; // 清理函数(先定义,避免在 performRestore 中引用未定义的变量) const cleanup = () => { if (ro) { ro.disconnect(); ro = null; } if (fallbackTimer !== null) { window.clearTimeout(fallbackTimer); fallbackTimer = null; } if (stabilityTimerRef.current !== null) { window.clearTimeout(stabilityTimerRef.current); stabilityTimerRef.current = null; } }; // 执行滚动恢复 const performRestore = (reason: string) => { if (settledRef.current) return; const maxScroll = Math.max(0, container.scrollHeight - container.clientHeight); const clampedTarget = Math.max(0, Math.min(target, maxScroll)); const prevBehavior = container.style.scrollBehavior; container.style.scrollBehavior = 'auto'; container.scrollTop = clampedTarget; container.style.scrollBehavior = prevBehavior; settledRef.current = true; if (clampedTarget < target) { log(`⚠ Restored to bottom (${clampedTarget}/${target}) - ${reason}`); } else { log(`✓ Restored scroll to ${clampedTarget} - ${reason}`); } // 清理资源 cleanup(); }; // 检查内容高度是否稳定 const checkStability = () => { const currentHeight = container.scrollHeight; const maxScroll = currentHeight - container.clientHeight; log('Height check:', { current: currentHeight, last: lastHeightRef.current, maxScroll, target, }); // 情况1: 内容已经足够高,可以直接恢复 if (maxScroll >= target) { performRestore('content sufficient'); return; } // 情况2: 高度稳定(不再增长) if (lastHeightRef.current > 0 && currentHeight === lastHeightRef.current) { // 高度不再变化,说明内容已渲染完成 // 即使 maxScroll < target,也恢复到最大可滚动位置 performRestore('content stable'); return; } // 更新上次高度 lastHeightRef.current = currentHeight; // 清除旧的稳定性计时器 if (stabilityTimerRef.current !== null) { window.clearTimeout(stabilityTimerRef.current); } // 设置新的稳定性计时器 // 如果在 stabilityDelay 时间内高度没有变化,认为内容已稳定 stabilityTimerRef.current = window.setTimeout(() => { if (!settledRef.current) { checkStability(); } }, stabilityDelay); }; // 立即检查一次 checkStability(); // 使用 ResizeObserver 监听容器尺寸变化 try { ro = new ResizeObserver(() => { if (!settledRef.current) { checkStability(); } }); ro.observe(container); log('ResizeObserver attached'); } catch (err) { log('ResizeObserver not available'); } // 超时保护 fallbackTimer = window.setTimeout(() => { if (!settledRef.current) { log('⏰ Timeout reached, forcing restore'); performRestore('timeout'); } }, timeout); cleanupRef.current = cleanup; return cleanup; }, [location.pathname, scrollPath, scrollPositions, isLoading, containerSelector, timeout, stabilityDelay, log]); // 普通模式:使用 useEffect useEffect(() => { if (!useKeepAlive) { performScrollRestore(); } }, [useKeepAlive, performScrollRestore]); // KeepAlive 模式:使用 useActivate useActivate(() => { if (useKeepAlive) { log('[KeepAlive] 组件激活,触发滚动恢复'); // 重置状态,因为可能是从其他页面返回 settledRef.current = false; lastHeightRef.current = 0; performScrollRestore(); } }); // KeepAlive 失活时清理 useUnactivate(() => { if (useKeepAlive && cleanupRef.current) { cleanupRef.current(); cleanupRef.current = null; } }); }3. 使用例子Library.tsx// src/components/Library.tsx import Cards from "@/components/Cards"; import { useScrollRestore } from "@/hooks/useScrollRestore"; export const Libraries: React.FC = () => { useScrollRestore('/libraries', { useKeepAlive: true });//更好支持KeepAlive,如果没使用KeepAlive,则直接传入路径即可。 return ( <Cards /> ) }4. 导航自定义LinkWithScrollSave.tsx// src/components/LinkWithScrollSave.tsx // 自定义 Link 组件,点击时保存滚动位置 import React, { KeyboardEvent } from 'react'; import { LinkProps, useLocation, useNavigate } from 'react-router-dom'; import { saveScrollPosition } from '@/utils/scrollUtils.ts'; export const LinkWithScrollSave: React.FC<LinkProps> = (props) => { const { to, onClick, children, ...rest } = props as any; const location = useLocation(); const navigate = useNavigate(); // 保持原有的滚动保存实现:只在导航前调用一次 saveScrollPosition const handleClick = (event: React.MouseEvent<any>) => { saveScrollPosition(location.pathname); if (props.onClick) { props.onClick(event); } }; const performNavigation = (target: any) => { try { if (typeof target === 'string' || typeof target === 'object') { navigate(target); } } catch (err) { // swallow navigation errors to avoid breaking UI console.error('navigation failed', err); } }; const handleDivClick = (event: React.MouseEvent<HTMLDivElement>) => { handleClick((event as unknown) as React.MouseEvent<HTMLAnchorElement>); performNavigation(to); }; const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); // @ts-ignore - reuse handleClick semantics handleClick((event as unknown) as React.MouseEvent<HTMLAnchorElement>); performNavigation(to); } }; // 渲染为非锚点容器,避免嵌套 <a>。不改动滚动的实现逻辑。 return ( <div role="link" tabIndex={0} onClick={handleDivClick} onKeyDown={handleKeyDown} {...(rest as any)} > {children} </div> ); }; export default LinkWithScrollSave;Layout.tsx// src/components/Layout.tsx // 使用自定义 Link 组件接管导航 import React, { useCallback } from 'react'; import { DashboardLayout, DashboardSidebarPageItem, type SidebarFooterProps, } from '@toolpad/core/DashboardLayout'; import { Outlet } from 'react-router'; import { LinkWithScrollSave } from '../LinkWithScrollSave'; import { NavigationPageItem } from '@toolpad/core/AppProvider'; export const Layout: React.FC = () => { const handleRenderPageItem = useCallback((item: NavigationPageItem, params: any) => { const to = `/${item.segment || ''}`; // 外层不渲染 <a>,而是使用可访问的 div 进行编程式导航, // 在导航前 LinkWithScrollSave 会保存滚动位置,避免嵌套 <a>。 return ( <LinkWithScrollSave to={to} style={{ textDecoration: 'none', color: 'inherit' }}> <DashboardSidebarPageItem item={item} {...params} />//保持原有样式 </LinkWithScrollSave> ); }, []); return ( <DashboardLayout renderPageItem={handleRenderPageItem} > <Outlet /> </DashboardLayout> ); }最终效果
2025年09月14日
21 阅读
0 评论
0 点赞