跳至主要內容

React国际化

zfh前端框架React小于 1 分钟约 272 字...

react-i18nopen in new window

安装

npm install react-i18next i18next --save

配置

// lang/index.js
import i18n from "i18next";
import { initReactI18next } from "react-i18next";

import translation_en from "./en.json";
import translation_zh from "./zh.json";

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

i18n
    .use(initReactI18next) // passes i18n down to react-i18next 初始化
    .init({
        resources,
        lng: "zh",
        interpolation: {
            escapeValue: false, // react already safes from xss
        },
    });

export default i18n;

index.tsx引入

import 'lang'

使用

hook

import {useTranslation} from "react-i18next";

// 
 const {t} = useTranslation()
 // zh.json
 //    "header": {
//        "slogan": "想去哪就去哪",
//        "title": "去哪里",
//        "register":"注册",
//        "signin":"登陆",
//        "searchPlaceHolder": "请输入旅游目的地、主题、或关键字",
//        "home_page": "旅游首页",
//        "weekend": "周末游",
//        "group": "跟团游",
//        "backpack": "自由行",
//        "private": "私家团",
//        "cruise": "邮轮",
//        "hotel": "酒店+景点",
//        "local": "当地玩乐",
//        "theme": "主题游",
//        "custom": "定制游",
//        "study": "游学",
//        "visa":"签证",
//        "enterprise":"企业游",
//        "high_end":"高端游",
//        "outdoor":"爱玩户外",
//        "insurance":"保险",
//        "shoppingCart": "购物车",
//        "signOut": "注销",
//        "welcome": "欢迎回来 "
//    },
 t('header.home_page')

Hoc

import React from 'react';

// the hoc
import { withTranslation } from 'react-i18next';

function MyComponent ({ t }) {
  return <h1>{t('header.home_page')}</h1>
}

export default withTranslation()(MyComponent);
上次编辑于:
本站勉强运行 小时
本站总访问量
網站計數器