Dictionary
useTranslations()
useTranslationsフックのAPIリファレンス
概要
useTranslations()
は翻訳辞書から文字列翻訳にアクセスするために使用されます。
<GTProvider>
でラップされたコンポーネント内で使用する必要があります。
const d = useTranslations(); // Get the translation function
d('greeting.hello'); // pass the id to get a translation
useTranslations()
は辞書を使用してすべての翻訳用コンテンツを保存します。
これは翻訳に<T>
コンポーネントを使用するのとは異なります。
翻訳に<T>
コンポーネントのみを使用することに興味がある場合、このドキュメントは関係ありません。
リファレンス
パラメータ
Prop | Type | Default |
---|---|---|
id?? | string | undefined |
説明
Prop | 説明 |
---|---|
id | すべての翻訳キーの前に付けるオプションのプレフィックス。ネストされた辞書値を扱う際に便利です。 |
戻り値
idが与えられると、対応するエントリの翻訳版を返す翻訳関数 d()
(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
フックに値'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>
);
}
Notes
useTranslations()
関数を使用すると、辞書の翻訳にアクセスできます。useTranslations()
フックは、<GTProvider>
コンポーネントでラップされたコンポーネント内でのみ使用できます。
次のステップ
- 辞書リファレンスで辞書の使用について詳しく学ぶ。
このガイドはいかがですか?