From 31ed4b7c2506b547cefd4694b7dba8d72fc20fe7 Mon Sep 17 00:00:00 2001 From: Caihaohan Date: Fri, 26 Dec 2025 16:50:08 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=AE=9E=E7=8E=B0=E4=B8=AD=E8=8B=B1?= =?UTF-8?q?=E6=96=87=E8=AF=AD=E8=A8=80=E5=88=87=E6=8D=A2=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新建 LocaleSwitcher 组件支持语言切换 - 使用 usePathname 保持当前页面路径 - 点击切换时自动更新 URL 语言前缀 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/app/[locale]/layout.tsx | 5 ++- src/components/locale/LocaleSwitcher.tsx | 41 ++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 src/components/locale/LocaleSwitcher.tsx diff --git a/src/app/[locale]/layout.tsx b/src/app/[locale]/layout.tsx index 07b5a25..83673ca 100644 --- a/src/app/[locale]/layout.tsx +++ b/src/app/[locale]/layout.tsx @@ -1,6 +1,7 @@ import { notFound } from "next/navigation" import { setRequestLocale } from 'next-intl/server' import Link from "next/link" +import { LocaleSwitcher } from "@/components/locale/LocaleSwitcher" const locales = ['zh', 'en'] @@ -72,9 +73,7 @@ export default async function LocaleLayout({ {/* Right side */}
- + = { + zh: '中文', + en: 'EN' +} + +export function LocaleSwitcher({ currentLocale }: { currentLocale: string }) { + const pathname = usePathname() + + // 移除当前语言前缀,获取基础路径 + const getBasePathname = () => { + const segments = pathname.split('/').filter(Boolean) + if (segments[0] && locales.includes(segments[0] as any)) { + return '/' + segments.slice(1).join('/') + } + return pathname + } + + const basePathname = getBasePathname() + + const switchLocale = (newLocale: string) => { + // 切换到另一种语言 + return `/${newLocale}${basePathname}` + } + + const otherLocale = currentLocale === 'zh' ? 'en' : 'zh' + + return ( + + {localeNames[currentLocale]} / {localeNames[otherLocale]} + + ) +}