fix: 实现中英文语言切换功能

- 新建 LocaleSwitcher 组件支持语言切换
- 使用 usePathname 保持当前页面路径
- 点击切换时自动更新 URL 语言前缀

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-12-26 16:50:08 +08:00
co-authored by Claude
parent 4abe6715bb
commit 31ed4b7c25
2 changed files with 43 additions and 3 deletions
+2 -3
View File
@@ -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 */}
<div className="hidden md:flex items-center space-x-4">
<button className="font-display text-sm font-bold hover:opacity-70">
/ EN
</button>
<LocaleSwitcher currentLocale={locale} />
<Link
className="bg-white dark:bg-surface-dark border-2 border-black dark:border-white px-4 py-2 font-display text-sm font-bold shadow-neo-sm hover:shadow-none hover:translate-x-[2px] hover:translate-y-[2px] transition-all"
href="#"
+41
View File
@@ -0,0 +1,41 @@
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
const locales = ['zh', 'en'] as const
const localeNames: Record<string, string> = {
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 (
<Link
href={switchLocale(otherLocale)}
className="font-display text-sm font-bold hover:opacity-70 transition-opacity"
>
{localeNames[currentLocale]} / {localeNames[otherLocale]}
</Link>
)
}