Dictionary

useDict()

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

概要

useDict() は、翻訳辞書から文字列の翻訳を取得するために使用されます。 これは、<GTProvider>でラップされたコンポーネント内で使用する必要があります。

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

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

リファレンス

パラメータ

PropTypeDefault
id??
string
undefined

説明

Prop説明
idすべての翻訳キーに追加するオプションのプレフィックスです。これはネストされた辞書の値を扱う際に便利です。

戻り値

与えられたidに基づいて、対応するエントリの翻訳版を返す翻訳関数 d()

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

基本的な使用法

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

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

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

辞書をGTProviderコンポーネントに渡す必要があります。

TranslateGreeting.jsx
import { useDict } from 'gt-react';
import dictionary from "./dictionary.json"
 
export default async function TranslateGreeting() {
  const d = useDict(); 
  return (
    <GTProvider dictionary={dictionary}>
      <p>
        {d('greeting')} // [!code highlight]
      </p>
    </GTProvider>
  );
}

変数の使用

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

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

dictionary.jsx
const dictionary = {
  greeting: "Hello, {userName}!", 
};
export default dictionary;
TranslateGreeting.jsx
import { useDict } from 'gt-react';
 
export default async function TranslateGreeting() {
  const d = useDict();
  
  // Hello Alice!
  const greetingAlice = d('greeting', { userName: "Alice" }); 
 
  return (
    <p>
      {greetingAlice} // Hello, Alice // [!code highlight]
    </p>
  );
}

プレフィックスの使用

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

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

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

UserDetails.jsx
import { useDict } from 'gt-react';
 
export default function UserDetails() {
  const d = useDict('prefix1.prefix2'); 
  return (
    <div>
      <p>{d('greeting')}</p> // greeting => prefix1.prefix2.greeting // [!code highlight]
    </div>
  );
}

メモ

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

次のステップ

このページについて