react项目实现国际化i18n

本篇教程将从零开始实现一个支持多语言功能的demo

0x00 准备

1. 通过create-react-app 新建项目

npx create-react-app my-app

2. 安装i18n所需的库

npm install react-i18next i18next i18next-browser-languagedetector i18next-http-backend --save

其中,i18next-browser-languagedetector库用于添加语言切换功能,可支持自动检测环境,切换到正确的语言,也可以在url中指定语言

3.修改App.js

实现一个用于展示的最小主页

import './App.css';

function App() {
  const { t, i18n } = useTranslation();

  return (
    <div className="App">
      <header className="App-header">
        <p>
          HelloWorld
        </p>
      </header>
    </div>
  );
}

export default App;

0x01 实现最简多语言功能

创建i18n.js,该文件在目录中与index.js同级。

import i18n from "i18next";
import { initReactI18next } from "react-i18next";

// the translations
// (tip move them in a JSON file and import them)
const resources = {
    en: {
        translation: {
            "HelloWorld": "HelloWorld"
        }
    },
    zh_CN: {
        translation: {
            "HelloWorld": "你好世界"
        }
    }
};

i18n
    .use(initReactI18next) // passes i18n down to react-i18next
    .init({
        resources,
        lng: "zh_CN", //设置当前语言

        keySeparator: false, // we do not use keys in form messages.welcome

        interpolation: {
            escapeValue: false // react already safes from xss
        }
    });

export default i18n;

不同语言的翻译内容填写在resources中,按照以上格式填写。上边我们对HelloWorld提供了两种语言的翻译,并设置当前语言为中文(代码zh_CN)

然后在index.js导入i18n.js

import './i18n';

编辑app.js

import './App.css';
import { useTranslation } from 'react-i18next';

function App() {
  const { t, i18n } = useTranslation();

  return (
    <div className="App">
      <header className="App-header">
        <p>
          {t("HelloWorld")}
        </p>
      </header>
    </div>
  );
}

export default App;

如上所示,t("HelloWorld")实现了对HelloWorld字符串的翻译。
运行项目

npm start

我们会看到主页显示出了"你好世界"

当我们把i18n.js的lng字段改为"en",再次刷新页面,会发现主页显示变为了"HelloWorld"

0x02 (待更新)

参考文档

react-i18next官方文档
i18next 官方文档
i18next-browser-languagedetector github项目主页
i18next-http-backend github项目主页

posted @ 2021-01-21 12:51  deepwzh  阅读(3800)  评论(0编辑  收藏  举报