Files
agent-park/src/components/locale/LocaleSwitcher.tsx
T
mzaxdandClaude 31ed4b7c25 fix: 实现中英文语言切换功能
- 新建 LocaleSwitcher 组件支持语言切换
- 使用 usePathname 保持当前页面路径
- 点击切换时自动更新 URL 语言前缀

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-26 16:50:08 +08:00

42 lines
1.0 KiB
TypeScript

'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>
)
}