Dictionary Translations

useTranslations

useTranslations 钩子的 API 参考

概述

useTranslations 用于从translation dictionary中获取字符串翻译。

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

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

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

参考资料

参数

Prop

Type

描述

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

返回值

翻译函数 d:传入一个 id,即可返回对应 Entry 的译文

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

示例

字典的基本用法

字典中的每个条目都会被翻译。

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

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

必须将字典传递给 GTProvider 组件。

TranslateGreeting.jsx
import { useTranslations } from 'gt-react';
import dictionary from "./dictionary.json"

export default function TranslateGreeting() {
  const d = useTranslations(); 
  return (
    <GTProvider dictionary={dictionary}>
      <p>
        {d('greeting')} // [!code highlight]
      </p>
    </GTProvider>
  );
}

使用变量

要传递值,你需要 (1) 为其指定一个标识符,(2) 在调用 d 函数时引用该标识符。

在此示例中,我们使用 {} 向翻译传入变量。 在字典中,我们将标识符指定为 {userName}

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

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

  return (
    <p>
      {greetingAlice} // 你好,Alice! // [!code highlight]
    </p>
  );
}

使用前缀

我们可以通过前缀仅翻译字典中的部分条目。

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

因为我们在 useTranslations 钩子中将 value 设为 'prefix1.prefix2',因此所有键都会加上 prefix1.prefix2 作为前缀:

UserDetails.jsx
import { useTranslations } from 'gt-react';

export default function UserDetails() {
  const d = useTranslations('prefix1.prefix2'); 
  return (
    <div>
      <p>{d('greeting')}</p> // greeting => prefix1.prefix2.greeting // [!code highlight]
    </div>
  );
}

注意

  • useTranslations 函数可用于访问字典中的翻译。
  • useTranslations 这个 hook 只能在由 <GTProvider> 组件 包裹的组件内使用。

下一步

本指南如何?