Dictionary Translations

useTranslations

useTranslations 钩子 API 参考

概览

useTranslations 用于从翻译字典中获取字符串的译文。

它必须在由 <GTProvider> 包裹的组件中使用。

const d = useTranslations(); // 获取翻译函数
d('greeting.hello'); // 传入 id 获取对应翻译

对于异步组件,请参阅 getTranslations

getTranslationsuseTranslations 使用 dictionary 来存储所有待翻译的内容。 这与使用 <T> 组件 进行翻译的方式不同。 如果你只打算使用 <T> 组件来完成翻译,那么本文档不适用。

参考资料

参数

Prop

Type

描述

Prop描述
id可选前缀,会添加到所有翻译键之前。适用于处理嵌套字典值的场景。

返回值

一个翻译函数 d,传入一个 id 后,将返回对应条目的翻译结果

(id: string, options?: DictionaryTranslationOptions) => React.ReactNode
名称类型描述
idstring要翻译的条目的 id
options?DictionaryTranslationOptions用于自定义 d 行为的翻译选项。

示例

字典的基础用法

字典中的每个 Entry 都会被 translate。

dictionary.jsx
const dictionary = {
  greeting: "Hello, Bob", 
};
export default dictionary;

当我们需要在客户端访问这些条目时,调用 useTranslations。 它会返回一个函数,该函数接收字典中的翻译键。

TranslateGreeting.jsx
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}

dictionary.jsx
const dictionary = {
  greeting: "你好,{userName}!", 
};
export default dictionary;
src/server/TranslateGreeting.jsx
import { useTranslations } from 'gt-next';

export default async function TranslateGreeting() {
  const d = useTranslations();
  
  // 嗨,Alice!
  const greetingAlice = d('greeting', { userName: "Alice" }); 

  return (
    <p>
      {greetingAlice}
    </p>
  );
}

使用前缀

我们可以通过前缀来仅翻译字典的某个子集。

dictionary.jsx
const dictionary = {
  prefix1: { 
    prefix2: { 
      greeting: "你好,Bob。",
    }
  }
};
export default dictionary;

由于我们在 useTranslations 钩子中添加了 'prefix1.prefix2' 作为 value,所有键都会自动带上 prefix1.prefix2 前缀:

UserDetails.jsx
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 函数允许你在客户端访问字典中的翻译。
  • useTranslations 仅可在由 <GTProvider> 组件 包裹的组件内部使用。

后续步骤

本指南如何?