useTranslations
useTranslations 钩子的 API 参考
概述
useTranslations 用于从translation dictionary中获取字符串的翻译。
它必须在由<GTProvider>包裹的组件中使用。
const d = useTranslations(); // 获取翻译函数
d('greeting.hello'); // 传入 id 获取对应翻译对于异步组件,请参阅 getTranslations。
getTranslations 和 useTranslations 使用 dictionary 来存储所有待翻译的内容。
这与使用 <T> 组件 进行翻译的方式不同。
如果你只计划使用 <T> 组件来完成翻译,那么本文档对你不适用。
参考资料
参数
Prop
Type
描述
| Prop | 描述 | 
|---|---|
| id | 可选的前缀,会添加到所有翻译键之前。适用于处理嵌套的字典值。 | 
返回值
一个翻译函数 d,传入一个 id,会返回对应 Entry 的翻译结果
(id: string, options?: DictionaryTranslationOptions) => React.ReactNode| 名称 | 类型 | 描述 | 
|---|---|---|
| id | string | 待翻译 Entry 的 id | 
| options? | DictionaryTranslationOptions | 自定义 d行为的 options。 | 
示例
字典的基本用法
字典中的每个 Entry 都会被翻译。
const dictionary = {
  greeting: "嗨,Bob", 
};
export default dictionary;当我们需要在客户端访问这些条目时,调用 useTranslations。
它会返回一个函数,该函数接受字典中某个翻译的键。
import { useTranslations } from 'gt-next';
export default async function TranslateGreeting() {
  const d = useTranslations(); 
  return (
    <p>
      {d('greeting')} // 嗨,Alice // [!code highlight]
    </p>
  );
}使用变量
要传递值,你需要 (1) 定义一个标识符,并且 (2) 在调用 d 函数时引用该标识符。
在这个示例中,我们使用 {} 向翻译传递变量。
在字典中,我们将标识符设为 {userName}。
const dictionary = {
  greeting: "您好,{userName}!", 
};
export default dictionary;import { useTranslations } from 'gt-next';
export default async function TranslateGreeting() {
  const d = useTranslations();
  
  // 嗨,Alice!
  const greetingAlice = d('greeting', { userName: "Alice" }); 
  return (
    <p>
      {greetingAlice}
    </p>
  );
}使用前缀
我们可以通过使用前缀,仅翻译字典中的部分条目。
const dictionary = {
  prefix1: { 
    prefix2: { 
      greeting: "嗨,Bob",
    }
  }
};
export default dictionary;因为我们在 useTranslations 钩子中添加了 value 值 'prefix1.prefix2',因此所有键都会带上 prefix1.prefix2 作为前缀:
import { useTranslations } from 'gt-next';
export default function UserDetails() {
  const d = useTranslations('prefix1.prefix2'); 
  return (
    <div>
      <p>{d('greeting')}</p> // greeting => prefix1.prefix2.greeting // [!code highlight]
    </div>
  );
}注意事项
- useTranslations函数可用于在客户端访问字典中的翻译。
- 只能在由 <GTProvider>组件 包裹的组件内使用useTranslations这个 hook。
后续步骤
- 若需在服务端进行翻译,请参阅 getTranslations。
- 如需了解如何使用 dictionaries,请查看 dictionaries 参考。
这份指南怎么样?

