Dictionary

useTranslations()

useTranslations hook 的 API 参考

概述

useTranslations() 用于从翻译字典中访问字符串翻译。 它必须在由 <GTProvider> 包装的组件内使用。

const d = useTranslations(); // Get the translation function
d('greeting.hello'); // pass the id to get a translation

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

export default async 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 hook 中添加了值 '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> 组件 包装的组件内使用。

下一步

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

这份指南怎么样?