前端开发中不同语言【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>
        ))}
相关推荐
丁总学Java14 分钟前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
活跃的煤矿打工人18 分钟前
【星海saul随笔】Ubuntu基础知识
linux·运维·ubuntu
It'sMyGo24 分钟前
Javascript数组研究09_Array.prototype[Symbol.unscopables]
开发语言·javascript·原型模式
懒羊羊大王呀25 分钟前
CSS——属性值计算
前端·css
李是啥也不会40 分钟前
数组的概念
javascript
无咎.lsy1 小时前
vue之vuex的使用及举例
前端·javascript·vue.js
fishmemory7sec1 小时前
Electron 主进程与渲染进程、预加载preload.js
前端·javascript·electron
fasewer1 小时前
第五章 linux实战-挖矿 二
linux·运维·服务器
fishmemory7sec1 小时前
Electron 使⽤ electron-builder 打包应用
前端·javascript·electron
楚灵魈1 小时前
[Linux]从零开始的网站搭建教程
linux·运维·服务器