5_国際化されたi18nextコンポーネントの導入

1. インストール
  • 依存関係をインストールするnpm i react-i18next i18next --S
2. 構成の国際化
  • ファイルの作成: i18n/zh.js
export default {
    
    
  username: "用户名",
  password: "密码",
};
  • ファイルの作成: i18n/en.js
export default {
    
    
  username: "username",
  password: "password",
};
  • ファイルの作成: i18n/index.js
import i18n from "i18next";
import {
    
     initReactI18next } from "react-i18next";
import zh from "./zh";
import en from "./en";

const resources = {
    
    
  en: {
    
    
    translation: en,
  },
  zh: {
    
    
    translation: zh,
  },
};

i18n.use(initReactI18next).init({
    
    
  resources,
  fallbackLng: "zh",
  lng: "zh",
  debug: true,
  interpolation: {
    
    
    escapeValue: false, // not needed for react as it escapes by default
  },
});

export default i18n;
3. エントリーファイルindex.jsでの参照有効化
import "./i18n";
4.使用する
  1. クラス コンポーネントで使用:
    withTranslation() 上位コンポーネントを使用して、コンテナ コンポーネントをラップします。
import {
    
     withTranslation } from "react-i18next";

class HomeLayout extends Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.t = props.t;
  }
  render() {
    
    
    return <div>{
    
    this.t("username")}</div>;
  }
}

export default withTranslation()(HomeLayout);
  1. 関数コンポーネントで使用されます。
import {
    
     useTranslation } from 'react-i18next';

export default (props) => {
    
    
  const {
    
     t } = useTranslation();

  return {
    
    
    <div>{
    
    t('username')}</div>
  }
}
  1. 言語の切り替え
    i18n. language: 現在の環境の言語を取得します。
    i18n.changeLanguage(): 言語の切り替え
import i18n from "i18next";

switchLang = () => {
    
    
  const lang = i18n.language;
  if (lang === "zh") {
    
    
    i18n.changeLanguage("en");
  } else {
    
    
    i18n.changeLanguage("zh");
  }
};

おすすめ

転載: blog.csdn.net/weixin_42465316/article/details/129292098