Dictionary
useTranslations()
useTranslations hook 的 API 参考
概述
useTranslations()
用于从翻译字典中访问字符串翻译。
它必须在由 <GTProvider>
包装的组件内使用。
const d = useTranslations(); // Get the translation function
d('greeting.hello'); // pass the id to get a translation
参考
参数
Prop | Type | Default |
---|---|---|
id?? | string | undefined |
描述
属性 | 描述 |
---|---|
id | 一个可选的前缀,用于添加到所有翻译键的前面。这对于处理嵌套字典值很有用。 |
返回值
一个翻译函数 d()
,给定一个 id,将返回相应条目的翻译版本
(id: string, options?: DictionaryTranslationOptions) => React.ReactNode
名称 | 类型 | 描述 |
---|---|---|
id | string | 要翻译的条目的 id |
options? | DictionaryTranslationOptions | 翻译选项,用于自定义 d() 的行为。 |
示例
基本用法
字典中的每个条目都会被翻译。
const dictionary = {
greeting: "Hello, Bob",
};
export default dictionary;
当我们想要访问这些条目时,我们调用 useTranslations()
。
这会返回一个函数,该函数接受字典中翻译的键。
你必须将字典传递给 GTProvider
组件。
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}
。
const dictionary = {
greeting: "Hello, {userName}!",
};
export default dictionary;
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>
);
}
使用前缀
我们可以使用前缀来只翻译字典的一个子集。
const dictionary = {
prefix1: {
prefix2: {
greeting: "Hello, Bob",
}
}
};
export default dictionary;
因为我们在 useTranslations
hook 中添加了值 'prefix1.prefix2'
,所有的键都会以 prefix1.prefix2
为前缀:
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>
组件 包装的组件内使用。
下一步
- 在字典参考中了解更多关于使用字典的信息。
这份指南怎么样?