Dictionary Translations

useTranslations

useTranslations 钩子的 API 参考

概述

useTranslations 用于从翻译字典中读取字符串的本地化文本。

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

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

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

参考资料

参数

Prop

Type

描述

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

返回值

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

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

示例

字典的基础用法

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

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) 定义一个标识符,并在调用 d 函数时 (2) 引用该标识符。

在此示例中,我们使用 {} 将变量传给翻译。 在字典中,我们定义标识符 {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> 组件 包裹的组件内部使用。

下一步

这份指南怎么样?

useTranslations