前端开发中不同语言【react-i18next】

目录

查看并设置语言

[单页面:html lang](#单页面:html lang)

​编辑

浏览器

自定义翻译:react-i18next

设置

模块:staticData.ts

散(重复利用):命名空间.json

应用

准备

html标签


查看并设置语言

单页面:html lang

  • 英语: <html lang="en">
  • 中文: <html lang="zh"><html lang="zh-CN">

"CN" 则表示该语言的特定区域,即中华人民共和国(China)。

更符合语言标准的规范

  • 西班牙语: <html lang="es">
  • 法语: <html lang="fr">
  • 日语: <html lang="ja">

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Webpage Title</title>
</head>
<body>
    <!-- Your webpage content goes here -->
</body>
</html>

浏览器

自定义翻译:react-i18next

设置

模块:staticData.ts

TypeScript 复制代码
export function getFeatures(lang: string){
  if(lang==='cn'){
    return [
      {
        title: '免费',
        description:  [
          '你好',
           ...
        ],
      },
      {
       ...
      }
    ]
  }else{
    return [
      {
        title: 'Free',
        description: [
          'hi~~~😄',
           ....
        ],
      },
      {
       ....
        ],
      }
    ]
  }

}

散(重复利用):命名空间.json

应用

  • t (translate) 函数: 这个函数用于翻译文本。

  • i18n 对象: 这是一个包含有关国际化设置的对象,其中包括当前语言环境等信息。

语言环境的判断和切换通常是由 i18n 对象处理的。

i18n.language 的默认值通常由 i18next 库的**language 配置项**决定。

在没有明确设置 language 配置项的情况下,i18next 会尝试根据浏览器的语言首选项(navigator.language)来设置默认语言

i18n.language; // 当前语言环境

i18n.changeLanguage('en'); // 切换到英语​​​​​​​

准备

javascript 复制代码
import { useTranslation } from 'react-i18next';
import { getFeatures } from './staticData';

export default function HomeContent() {
  const { t, i18n } = useTranslation(['home', 'login']);
  const features = getFeatures(['zh', 'zh-CN', 'cn'].includes(i18n.language) ? 'cn' : 'en')

html标签

html 复制代码
<h1 className="font-bold text-2xl">{t('Sign in/Sign up')}</h1>
{features?.map((item, index) => (
          <div className='flex flex-col items-center p-4 md:w-1/2' key={item.title}>
            <div className=' min-w-full h-full bg-[#2A2935] rounded-lg p-4'>
              <div className=' text-2xl leading-loose md:leading-tight'>{item.title}
                {item.subtitle && <span className=' text-xs text-gray-400 ml-2'>( {item.subtitle} )</span>}
              </div>
              {item.description.map((item, index) => (
                <div className=' text-xs text-gray-400 leading-relaxed' key={index}>- {item}</div>
              ))}
            </div>
          </div>
        ))}
相关推荐
JustHappy15 分钟前
我汇总了身边朋友的经历才发现,其实第一份实习是最难找的......
前端·后端·面试
星栈27 分钟前
Dioxus 的响应式系统:`Signal`、`Memo`、`Effect` 和异步状态到底该怎么分工
前端·前端框架
yingyima28 分钟前
Java 正则表达式:比你想象的更强大
前端
A小辣椒2 小时前
TShark:Wireshark CLI 功能
linux
yuanyxh3 小时前
macOS 应用 - 纯对话生成
前端·macos·ai编程
大家的林语冰3 小时前
ES5 凉凉,Babel 8 正式发布,默认不再编译为 ES5 和 CJS......
前端·javascript·前端工程化
光影少年5 小时前
react批量更新、同步/异步更新场景
前端·react.js·掘金·金石计划
假如让我当三天老蒯5 小时前
模块化:ES Module 与 CommonJS 的区别
前端·面试
用户40950115773175 小时前
Private Forge v2.0 发布:12大前端业务场景技能系统
前端
A小辣椒6 小时前
TShark:基础知识
linux