React多语言支持

130 阅读1分钟

安装

yarn add i18next react-i18next

配置 i18n

/i18n/index.ts

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import resources from "./resources";

i18n
    .use(initReactI18next)
    .init({
        resources,
        lng: localStorage.getItem('lng') || 'en'
        interpolation: {
            escapeValue: false // react already safes from xss
        }
    });

export default i18n;

/i18n/resources.ts

const resources = {
    zh: {
        home: {
            demo: "演示"
        }
    },
    en: {
        home: {
            demo: "demo"
        }
    }
};

export default resources

首页 index.tsx

import { useTranslation } from "react-i18next";
import i18n from "../i18n";
const setLng = (str: string) => {
    localStorage.setItem('lng', str)
    window.location.reload()
}
export default () => {
    const { t } = useTranslation("home", { i18n });
    return (
        <>
            <h1>{t('demo')}</h1>
            <button onClick={() => {
                setLng('zh')
              }}>中文</button>
            <button onClick={() => {
                setLng('en')
            }}>English</button>
        </>
    )
}

示例代码: gitee.com/codetyphon/…