react-i18next用法

73 阅读1分钟

安装依赖

npm install react-i18next i18next --save

i18next提供翻译功能,react-i18next让i18next在react中使用

调用方法

  1. 在src目录下创建中/英文翻译文件

image.png

提示:由于必须使用zh-CN(遵循BCP 47标准,国家/地区代码大写),此处为了统一,文件夹名用的zh-CN,而不是zh-cn

zh-CN/translation.josn

{
    "i18next": {
        "title": "首页",
        "welcome": "欢迎来到{{name}}",
        "welcome1": "欢迎来到<0>{{name}}</0> <1>{{name1}}</1>",
        "welcome2": "欢迎来到<span>{{name}}</span> <bold>{{name1}}</bold>"
     }
}

en/translation.json

{
    "i18next": {
        "title": "Home",
        "welcome": "Welcome to the {{name}}",
        "welcome1": "Welcome to the <0>{{name}}</0> <1>{{name1}}</1>",
        "welcome2": "Welcome to the <span>{{name}}</span> <bold>{{name1}}</bold>"
     }
}

2. 在src目录下创建i18n.ts

import i18n from "i18next";
import Cookies from 'js-cookie';
import { initReactI18next } from "react-i18next";
import en from './locales/en/translation.json';
import zhCN from './locales/zh-CN/translation.json';
i18n.use(initReactI18next).init({
  lng: "zh-CN",
  fallbackLng: false,
  debug: true,
  resources: {
    // react-i18next,必须使用zh-CN(遵循BCP 47标准,国家/地区代码大写),使用zh-cn语言包不加载
    "zh-CN": {
      translation: zhCN,
    },
    en: {
      translation: en,
    },
  },
  interpolation: { escapeValue: false },
});
export default i18n;

3. 在src/main.tsx中引入i18n

import "./i18n";

4. 在src/view/Home.tsx调用

import { Trans, useTranslation } from "react-i18next";

function Home() {
  const { t } = useTranslation();
  return (
    <div>
      {/* 普通翻译 */}
      <div>{t("i18next.title")}</div>
      {/* 带参数的翻译 */}
      <div>{t("i18next.welcome", { name: "John" })}</div>
      <div>
        {/* 带标签的翻译,标签以数组形式传递 */}
        <Trans
          i18nKey="i18next.welcome1"
          values={{ name: "John", name1: "Doe" }}
          components={[
            <span className="text-blue" key={0} />,
            <span className="text-red" key={1} />,
          ]}
        />
      </div>
      <div>
        {/* 带标签的翻译,标签以对象形式传递 */}
        <Trans
          i18nKey="i18next.welcome2"
          values={{ name: "John", name1: "Doe" }}
          components={{
            span: <span className="text-blue" key={0} />,
            bold: <span className="text-bold" key={1} />,
          }}
        />
      </div>
    </div>
  );
}

export default Home;