useTranslations
useTranslations 钩子 API 参考
概览
useTranslations 用于从翻译字典中获取字符串的译文。
它必须在由 <GTProvider> 包裹的组件中使用。
const d = useTranslations(); // 获取翻译函数
d('greeting.hello'); // 传入 id 获取对应翻译对于异步组件,请参阅 getTranslations。
getTranslations 和 useTranslations 使用 dictionary 来存储所有待翻译的内容。
这与使用 <T> 组件 进行翻译的方式不同。
如果你只打算使用 <T> 组件来完成翻译,那么本文档不适用。
参考资料
参数
Prop
Type
描述
| Prop | 描述 |
|---|---|
id | 可选前缀,会添加到所有翻译键之前。适用于处理嵌套字典值的场景。 |
返回值
一个翻译函数 d,传入一个 id 后,将返回对应条目的翻译结果
(id: string, options?: DictionaryTranslationOptions) => React.ReactNode| 名称 | 类型 | 描述 |
|---|---|---|
id | string | 要翻译的条目的 id |
options? | DictionaryTranslationOptions | 用于自定义 d 行为的翻译选项。 |
示例
字典的基础用法
字典中的每个 Entry 都会被 translate。
const dictionary = {
greeting: "Hello, Bob",
};
export default dictionary;当我们需要在客户端访问这些条目时,调用 useTranslations。
它会返回一个函数,该函数接收字典中的翻译键。
import { useTranslations } from 'gt-next';
export default async function TranslateGreeting() {
const d = useTranslations();
return (
<p>
{d('greeting')} // 嗨,Alice // [!code highlight]
</p>
);
}使用变量
要传递值,你需要 (1) 设定一个标识符,并在 (2) 调用 d 函数时引用该标识符。
在此示例中,我们使用 {} 向翻译传入变量。
在字典中,我们设定标识符 {userName}。
const dictionary = {
greeting: "你好,{userName}!",
};
export default dictionary;import { useTranslations } from 'gt-next';
export default async function TranslateGreeting() {
const d = useTranslations();
// 嗨,Alice!
const greetingAlice = d('greeting', { userName: "Alice" });
return (
<p>
{greetingAlice}
</p>
);
}使用前缀
我们可以通过前缀来仅翻译字典的某个子集。
const dictionary = {
prefix1: {
prefix2: {
greeting: "你好,Bob。",
}
}
};
export default dictionary;由于我们在 useTranslations 钩子中添加了 'prefix1.prefix2' 作为 value,所有键都会自动带上 prefix1.prefix2 前缀:
import { useTranslations } from 'gt-next';
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>组件 包裹的组件内部使用。
后续步骤
- 如需进行 server-side 翻译,请参阅
getTranslations。 - 在 dictionaries 参考中了解更多关于使用 dictionaries 的信息。
本指南如何?