Dictionary

useTranslations()

useTranslationsフックのAPIリファレンス

概要

useTranslations()翻訳辞書から文字列翻訳にアクセスするために使用されます。 <GTProvider>でラップされたコンポーネント内で使用する必要があります。

const d = useTranslations(); // 翻訳関数を取得
d('greeting.hello'); // IDを渡して翻訳を取得

非同期コンポーネントについては、getTranslations()を参照してください。

getTranslations()useTranslations()辞書を使用して翻訳用のすべてのコンテンツを保存します。 これは翻訳に<T>コンポーネントを使用するのとは異なります。 翻訳に<T>コンポーネントのみを使用することに興味がある場合、このドキュメントは関係ありません。

リファレンス

パラメータ

PropTypeDefault
id??
string
undefined

説明

プロパティ説明
idすべての翻訳キーの前に付けるオプションのプレフィックス。ネストされた辞書値を扱う際に便利です。

戻り値

idが与えられると、対応するエントリの翻訳版を返す翻訳関数 d()

(id: string, options?: DictionaryTranslationOptions) => React.ReactNode
名前説明
idstring翻訳されるエントリのid
options?DictionaryTranslationOptionsd() の動作をカスタマイズする翻訳オプション。

基本的な使用方法

辞書内のすべてのエントリが翻訳されます。

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

これらのエントリにアクセスしたい場合(クライアント側で)、useTranslations()を呼び出します。 これは辞書から翻訳のキーを受け取る関数を返します。

TranslateGreeting.jsx
import { useTranslations } from 'gt-next';

export default async function TranslateGreeting() {
  const d = useTranslations(); 
  return (
    <p>
      {d('greeting')} // Hello, Alice // [!code highlight]
    </p>
  );
}

変数の使用

値を渡すためには、(1) 識別子を割り当て、(2) d()関数を呼び出すときに識別子を参照する必要があります。

この例では、{}を使用して翻訳に変数を渡します。 辞書では、識別子{userName}を割り当てます。

dictionary.jsx
const dictionary = {
  greeting: "Hello, {userName}!", 
};
export default dictionary;
src/server/TranslateGreeting.jsx
import { useTranslations } from 'gt-next';

export default async function TranslateGreeting() {
  const d = useTranslations();
  
  // Hello Alice!
  const greetingAlice = d('greeting', { userName: "Alice" }); 

  return (
    <p>
      {greetingAlice}
    </p>
  );
}

プレフィックスの使用

プレフィックスを使用して、辞書のサブセットのみを翻訳することができます。

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

useTranslationsフックに値'prefix1.prefix2'を追加したため、すべてのキーにprefix1.prefix2がプレフィックスとして付けられます:

UserDetails.jsx
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>
  );
}

Notes

  • useTranslations()関数を使用すると、クライアントサイドで辞書の翻訳にアクセスできます。
  • useTranslations()フックは、<GTProvider>コンポーネントでラップされたコンポーネント内でのみ使用できます。

次のステップ

このガイドはいかがですか?