"use client"
声明)npm install next-intl
.
├── app
│ ├── [locale]
│ │ ├── layout.tsx # 设置 IntlProvider
│ │ ├── page.tsx
├── messages
│ ├── en.json
│ ├── zh.json
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 (
{children}
);
}
useTranslations
components/Greeting.tsx
'use client';
import { useTranslations } from 'next-intl';
export default function Greeting() {
const t = useTranslations('user'); // 对应 messages/en.json 中的 "user" 命名空间
return {t('greeting', { name: 'David' })}
;
}
{
"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 ;
}
对应 messages:
{
"form": {
"submit": "Submit"
}
}
// app/[locale]/page.tsx
import Greeting from '@/components/Greeting';
export default function HomePage() {
return (
);
}
用法 | 用于 | 示例函数 |
---|---|---|
getTranslations |
服务端组件 (page.tsx , layout.tsx ) |
const t = await getTranslations('home') |
useTranslations |
客户端组件 ("use client" 组件) |
const t = useTranslations('user') |