Dictionary

useDict()

useDict 钩子的 API 参考

概述

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

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

useDict() 使用字典来存储所有翻译内容。 这与使用<T> 组件进行翻译不同。 如果您只对使用 <T> 组件进行翻译感兴趣,那么本文档不相关。

参考

参数

PropTypeDefault
id??
string
undefined

描述

Prop描述
id一个可选的前缀,用于添加到所有翻译键之前。这对于处理嵌套字典值非常有用。

返回值

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

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

示例

基本用法

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

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

当我们想要访问这些条目时,我们调用 useDict()。 这将返回一个函数,该函数接受字典中翻译的键。

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

TranslateGreeting.jsx
import { useDict } from 'gt-react';
import dictionary from "./dictionary.json"
 
export default async function TranslateGreeting() {
  const d = useDict(); 
  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 { useDict } from 'gt-react';
 
export default async function TranslateGreeting() {
  const d = useDict();
  
  // 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;

因为我们将值 'prefix1.prefix2' 添加到 useDict 钩子中,所有的键都被加上了 prefix1.prefix2 的前缀:

UserDetails.jsx
import { useDict } from 'gt-react';
 
export default function UserDetails() {
  const d = useDict('prefix1.prefix2'); 
  return (
    <div>
      <p>{d('greeting')}</p> // greeting => prefix1.prefix2.greeting // [!code highlight]
    </div>
  );
}

注意事项

  • useDict() 函数允许您访问字典翻译。
  • useDict() 钩子只能在由 <GTProvider> 组件 包裹的组件中使用。

下一步

在本页面