当前位置: 首页 > news >正文

国际化语言,多语言三种方式

  1. 可以用透传的方式,自己写local的json文件,不需要配置什么,直接传,自己写方法

  1. i18n nextjs

  1. i18n umi4

一、透传的方式 export const AppContext = React.createContext<any>({})

  1. app.tsx 用context包裹

import type { AppProps } from 'next/app'
import React, { useState } from 'react';
import { appWithTranslation } from 'next-i18next'import enUs from '../public/locales/EN/common.json';
import zhCN from '../public/locales/ZH_CN/common.json';export const AppContext = React.createContext<any>({})
const App = ({ Component, pageProps }: AppProps) => {const [locale, setLocal] = useState(zhCN);return <AppContext.Provider value={{locale,setLocal}} ><Component {...pageProps} /></AppContext.Provider>
}
export default appWithTranslation(App)
  1. 写local.json文件

//中文{"welcome": "欢迎"
}//英文{"welcome": "welcome"
}
  1. 封装方法

import { useContext } from "react";
import { AppContext } from "../pages/_app";const useLocale = () => {const { locale } = useContext(AppContext);const getLocale = (key: string) => {if (!key) throw new Error(`key is not defined`);const keys = key.split('.');let nowValue = locale;let res = null;try {keys.forEach((item, index) => {const subItem = nowValue[item];if (index === keys.length - 1) {res = subItem;} else {if (typeof subItem === 'object' && subItem !== null) {nowValue = subItem;} else {res = null;console.log(res)}}});} catch (err) {console.log(err)}return res;}return getLocale;
}export default useLocale;

  1. 使用:

  const Home = (props:any) => {const { setLocal } = useContext(AppContext);const getLocale = useLocale();// 语言切换const handleLanguageChange = (value: string) => {if(value==='EN'){setLocal(enUs)}if(value==='ZH_CN'){setLocal(zhCN)}};
return({
<>
<p> { getLocale('welcome')}</p>  //应用<div className={styles.selectBtn}><SelectdefaultValue="ZH_CN"onChange={handleLanguageChange}getPopupContainer={() => document.getElementById('area') !}options={[{ value: "EN", label: "英文" },{ value: "ZH_CN", label: "中文" },]}/></div>}
</>
})

二、场景二:next.js下载配置

npm install next-i18next
  1. 根目录下新建文件 next-i18next.config.js

module.exports = {i18n: {defaultLocale: "en",locales: ["en",  "zh-CN"],localePath: "./locales",},
};
  1. next.config.js

const { i18n } = require("./next-i18next.config");const nextConfig = {// other stuffi18n,
};module.exports = nextConfig;
  1. local文件夹,文件夹在public下面新建locales

.
└── locales├── en|   └── common.json|   └── home.json└── zh-CH|   └── common.json|   └── home.json
  1. 高阶组件引用:pages/_app.jsx

import { appWithTranslation } from "next-i18next";
import Header from "../components/Header";
import "../styles/globals.css";function MyApp({ Component, pageProps }) {return (<><Header /><Component {...pageProps} /></>);
}export default appWithTranslation(MyApp);
  1. index.tsx文件里面使用 pages/index.jsx

import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useRouter } from "next/router";// export default function Home...const { route, asPath, push } = useRouter();// 语言切换const handleLanguageChange = (value: string) => {push(route, asPath, {locale: value as any})};<div className={styles.selectBtn}><SelectdefaultValue="ZH_CN"onChange={handleLanguageChange}getPopupContainer={() => document.getElementById('area') !}options={[{ value: "EN", label: "英文" },{ value: "ZH_CN", label: "中文" },]}/></div>export async function getStaticProps({ locale }) {return {props: {...(await serverSideTranslations(locale, ["common", "home"])),// Will be passed to the page component as props},};
}
  1. pages/index.jsx

// other imports
import { useTranslation } from "next-i18next";export default function Home() {// We want to get the translations from `home.json`const { t } = useTranslation("home");// Get the translation for `greeting` keyreturn <main>{t("welcome")}</main>;
}// export async function getStaticProps...

此处:nextjs的多语言就能使用了

如果我们希望它使用默认的语言环境值(在我们的例子中是en),我们可以省略一些翻译键。

还有个例子可以参考:

{"title": "保持最新状态","form": {"email": "电子邮箱","action": {"cancel": "取消"}}
}
import { useTranslation } from "next-i18next";
import React from "react";const SubscribeForm = () => {const { t } = useTranslation("newsletter");return (<section><h3>{t("title")}</h3><h4>{t("subtitle")}</h4><form><input placeholder={t("form.firstName")} /><input placeholder={t("form.email")} /><button>{t("form.action.signUp")}</button><button>{t("form.action.cancel")}</button></form>{/* For styling only */}<style jsx>{`form {max-width: 300px;display: flex;flex-direction: column;}input {margin-bottom: 0.5rem;}`}</style></section>);
};export default SubscribeForm;

next 如果只打包静态页面,i18n会报错,可以用第一种透传的方式。

三、场景三:umi里面的多语言i18n

  1. index.tsx

import { SelectLang } from '@umijs/max';<SelectLang className={styless.action} />
  1. locales.js和前面一样{ },如果是locales.ts的话,注意export default暴露这样写:

export default{
"welcome":"welcome"
}
  1. umirc.ts

import { defineConfig } from '@umijs/max';
import routes from './src/routes/index';
import proxy from './config/proxy';
const { APP_ENV } = process.env;export default defineConfig({history: { type: 'hash' },dva: {},antd: {},access: {},model: {},initialState: {},request: {},locale: {antd: true, // 如果项目依赖中包含 `antd`,则默认为 true  一定要设置 否则SelectLang不显示baseNavigator: true,baseSeparator: '-',default: 'zh-CN',title: false,useLocalStorage: true,},ignoreMomentLocale: true,// Option+Click/Alt+Click 点击组件跳转至编辑器源码位置clickToComponent: { editor: 'vscode' },
});
  1. 封装hooks

import { getIntl } from "@umijs/max";let intl = getIntl ();function useLocale(name:string,values?:{[key:string]:any}):string{if(!name)return '';return intl.formatMessage({id:name},{...values})|| name;
}export default useLocale;
  1. index.tsx

<div> {useLocale('welcome')}</div>

如果没有封装hook,可以使用 FormattedMessage ,index.tsx里:

import { FormattedMessage, useIntl } from '@umijs/max';const Home = ()=>{const { formatMessage } = useIntl();
return({<p>{formatMessage({ id: 'welcome' })}</p>})}

ok,三种解决国际化多语言的方式。

http://www.lryc.cn/news/6088.html

相关文章:

  • C++——哈希3|位图
  • 75 error
  • ESP-C3入门8. 连接WiFi并打印信息
  • 使用python将EXCEL表格中数据转存到数据库
  • 【C++】类和对象(三)
  • vTESTstudio - VT System CAPL Functions - General/Trigger Function
  • IDEA 快捷键
  • 2023新华为OD机试题 - 入栈出栈(JavaScript) | 刷完必过
  • 微信公众号扫码授权登录思路
  • 数据结构与算法基础-学习-10-线性表之顺序栈的清理、销毁、压栈、弹栈
  • Hazel游戏引擎(005)
  • 牛客网Python篇数据分析习题(四)
  • 盲盒如何创业?
  • 第1集丨Java中面向对象相关概念汇总
  • 高性能(二)
  • Allegro如何实现同一个屏幕界面分屏显示操作指导
  • 前后端一些下载与配置(第二篇 第10天过后)nuxt banner redis 短信服务
  • OSG三维渲染引擎编程学习之四十八:“第五章:OSG场景渲染” 之 “5.6 多重纹理映射”
  • 对Node.js 的理解?优缺点?应用场景?
  • Bean的生命周期
  • Python学习-----函数2.0(函数对象,名称空间,作用域-->全局变量与局部变量)
  • Java中Json字符串和Java对象的互转
  • 代码随想录NO42 | 动态规划_Leetcode70. 爬楼梯 (进阶) 322. 零钱兑换 279.完全平方数
  • 【C++从入门到放弃】初识C++(基础知识入门详解)
  • 企业工程项目管理系统源码+spring cloud 系统管理+java 系统设置+二次开发
  • 【GPLT 三阶题目集】L3-016 二叉搜索树的结构
  • 核心交换机安全多业务高性能万兆交换机
  • Android APK 签名打包原理分析(三)【静默安装的实现方案】
  • mulesoft MCIA 破釜沉舟备考 2023.02.14.05
  • 结构体的三种定义方法、结构体类型名(可选标志符)什么时候可以省略