Dictionary

useTranslations()

useTranslations hook 的 API 参考

概览

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

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

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

useTranslations() 使用字典来存储所有待翻译的内容。 这与使用 <T> 组件 进行翻译的方式不同。 如果你只打算使用 <T> 组件进行翻译,则本篇文档无需阅读。

参考

参数

PropTypeDefault
id??
string
undefined

描述

属性描述
id一个可选的前缀,用于添加到所有翻译键的前面。这对于处理嵌套字典值很有用。

返回值

一个翻译函数 d(),给定一个 id,将返回相应条目的翻译版本

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

示例

基本字典用法

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

dictionary.jsx
const dictionary = {
  greeting: "Hello, 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: "Hello, {userName}!", 
};
export default dictionary;
TranslateGreeting.jsx
import { useTranslations } from 'gt-react';

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

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

使用前缀

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

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

因为我们在 useTranslations 钩子中传入了 '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() 钩子只能在被 <GTProvider> 组件 包装的组件内使用。

下一步

  • 字典参考中了解更多关于使用字典的信息。

这份指南怎么样?