[特殊字符] useTranslations 客户端使用教程(Next.js + next-intl)
✅ 适用场景
- 用于 客户端组件(加了
"use client"
声明) - 配合 React Hooks 使用翻译
- 动态渲染、事件响应等需要在客户端处理的地方
📦 安装(如未安装)
npm install next-intl
📁 项目结构参考
.
├── app
│ ├── [locale]
│ │ ├── layout.tsx # 设置 IntlProvider
│ │ ├── page.tsx
├── messages
│ ├── en.json
│ ├── zh.json
✨ 1. 设置 Provider(app/[locale]/layout.tsx
)
这是必须步骤,让 useTranslations
能获取到当前语言环境。
import { NextIntlClientProvider, useMessages } from 'next-intl';export default function LocaleLayout({children,params: { locale }
}: {children: React.ReactNode;params: { locale: string };
}) {const messages = useMessages(); // 服务器端提供翻译内容return (<NextIntlClientProvider locale={locale} messages={messages}>{children}</NextIntlClientProvider>);
}
💡 2. 客户端组件中使用 useTranslations
📄 components/Greeting.tsx
'use client';import { useTranslations } from 'next-intl';export default function Greeting() {const t = useTranslations('user'); // 对应 messages/en.json 中的 "user" 命名空间return <p>{t('greeting', { name: 'David' })}</p>;
}
🌍 messages/en.json 示例:
{"user": {"greeting": "Hello, {name}!"}
}
🗣 渲染结果为:Hello, David!
🎉 支持嵌套命名空间
const t = useTranslations();
t('user.greeting', { name: 'Alice' });
📌 注意事项
useTranslations
只能在客户端组件中使用,必须加"use client"
。- 如果没有正确设置
NextIntlClientProvider
,会抛出错误。 - 参数占位
{name}
支持动态替换。
✅ 用于按钮、交互、表单等
'use client';import { useTranslations } from 'next-intl';export function SubmitButton() {const t = useTranslations('form');return <button>{t('submit')}</button>;
}
对应 messages:
{"form": {"submit": "Submit"}
}
🧩 示例组合:page.tsx + 客户端组件
// app/[locale]/page.tsx
import Greeting from '@/components/Greeting';export default function HomePage() {return (<div><Greeting /></div>);
}
🧠 总结
用法 | 用于 | 示例函数 |
---|---|---|
getTranslations | 服务端组件 (page.tsx , layout.tsx ) | const t = await getTranslations('home') |
useTranslations | 客户端组件 ("use client" 组件) | const t = useTranslations('user') |