useTranslations
useTranslationsフックのAPIリファレンス
概要
useTranslations は、translation dictionary から文字列の翻訳を取得するために使います。
<GTProvider> でラップされたコンポーネント内でのみ使用できます。
const d = useTranslations(); // 翻訳用の関数を取得する
d('greeting.hello'); // 翻訳を取得するために id を渡すuseTranslations は、翻訳対象のすべてのコンテンツを保存するために dictionary を使用します。
これは、翻訳に <T> コンポーネント を使用する方法とは異なります。
翻訳に <T> コンポーネントのみを使用する予定であれば、このドキュメントは対象外です。
リファレンス
パラメータ
Prop
Type
説明
| Prop | 説明 |
|---|---|
id | すべての翻訳キーの先頭に付与する任意のプレフィックス。ネストされた dictionary の value を扱う際に便利です。 |
返り値
id を渡すと、対応する Entry の翻訳を返す翻訳関数 d
(id: string, options?: DictionaryTranslationOptions) => React.ReactNode| 名称 | 型 | 説明 |
|---|---|---|
id | string | 翻訳するEntryのid |
options? | DictionaryTranslationOptions | d の動作をカスタマイズするための翻訳options。 |
例
基本的な dictionary の使い方
dictionary のすべての Entry は翻訳されます。
const dictionary = {
greeting: "こんにちは、ボブ",
};
export default dictionary;これらのエントリにアクセスするには、useTranslations を呼び出します。
これは、dictionary 内の翻訳キーを受け取る関数を返します。
GTProvider コンポーネントに dictionary を渡す必要があります。
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>
);
}variablesの使用
値を渡すには、(1) 識別子を割り当て、(2) d 関数を呼び出す際にその識別子を参照する必要があります。
この例では、{} を使って variables を翻訳に渡します。
dictionary では、識別子 {userName} を割り当てます。
const dictionary = {
greeting: "こんにちは、{userName}さん!",
};
export default dictionary;import { useTranslations } from 'gt-react';
export default function TranslateGreeting() {
const d = useTranslations();
// アリスさん、こんにちは!
const greetingAlice = d('greeting', { userName: "Alice" });
return (
<p>
{greetingAlice} // アリスさん、こんにちは // [!code highlight]
</p>
);
}プレフィックスの使用
プレフィックスを使って、dictionary の一部だけを翻訳できます。
const dictionary = {
prefix1: {
prefix2: {
greeting: "こんにちは、ボブ",
}
}
};
export default dictionary;useTranslations フックに 'prefix1.prefix2' という value を追加したため、すべてのキーには 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関数を使うと、dictionary の翻訳にアクセスできます。useTranslationsフックは、<GTProvider>コンポーネント でラップされたコンポーネント内でのみ使用できます。
次の手順
このガイドはいかがですか?