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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值