React国际化中英文切换实现

目录

概况

安装

文件结构

引入

使用

正常使用

传参使用


概况

react-intl-universal 是一个国际化库,专门为 React 应用提供多语言支持。与 React 原生的 react-intl 相比,react-intl-universal 支持从远程服务器加载语言包,动态切换语言,并且可以不依赖于 React 组件。

GitHub地址:

GitHub - alibaba/react-intl-universal: Internationalize React apps. Not only for Component but also for Vanilla JS.Internationalize React apps. Not only for Component but also for Vanilla JS. - alibaba/react-intl-universalhttps://github.com/alibaba/react-intl-universal

安装

可以通过 npm 或 yarn 来安装该依赖,命令如下:

复制代码
npm install react-intl-universal --save
# 或者
yarn add react-intl-universal

文件结构

安装依赖完成后就可以创建对应的文件夹以用来保存各类语种的翻译。

一般情况下,都存放在根目录==> src ==> locales 目录下。

这里我只做了中英文的翻译,如果你想添加更多语种则可以添加对应的json文件。

注意!这里创建的文件类型是json而不是js。

引入

初始化react-intl-universal插件,

通常在应用启动时(如在 componentDidMountuseEffect 中)初始化 react-intl-universal,并加载对应的语言包。

一般情况下这个引入过程都应该放在入口文件上,或者顶级layout中,以方便做中英文切换的按钮。

javascript 复制代码
import React, { Component } from 'react'
import intl from 'react-intl-universal';
const locales = {
  "en": require('../locales/en-US.json'),
  "zh": require('../locales/zh-CN.json'),
};

export default class index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentLocale: this.props?.baseInfo?.currentLocale || 'zh',
    }
  }
  componentDidMount() {
    this.loadLocales()
  }
  loadLocales() {
    const { currentLocale } = this.state
    intl.init({
      currentLocale: currentLocale,
      locales,
    }).then(() => {});
  }

  render() {
    return (

    )
  }
}

使用

假如我现在有两个文件,一个en-US.json,一个zh-CN.json。内容分别如下。

javascript 复制代码
// en-US.json
{
  "HELLO": "Hello!",
  "WELCOME": "Welcome to {place}."
}

// zh-CN.json
{
  "HELLO": "你好!",
  "WELCOME": "欢迎来到{place}。"
}

正常使用

在对应组件中引入 intl 然后使用 intl.get 就可以获取对应的翻译内容。

注意!这里get方法内传入的字符串,必须与zh-CN.json和en-US.json中对应翻译的ID一致,且区分大小写。

javascript 复制代码
import intl from 'react-intl-universal';


const greeting = intl.get('HELLO');
console.log(greeting); // 输出: "Hello!" 或 "你好!"

传参使用

基本用法一致,传参的话可以根据当前语言也做一下判断。

javascript 复制代码
import intl from 'react-intl-universal';


const greeting = intl.get('WELCOME',{place: '百京'});
console.log(greeting); // 输出: "Welcome to 百京" 或 "欢迎来到百京"
相关推荐
2601_949809591 分钟前
flutter_for_openharmony家庭相册app实战+相册详情实现
javascript·flutter·ajax
qq_177767375 分钟前
React Native鸿蒙跨平台通过Animated.Value.interpolate实现滚动距离到动画属性的映射
javascript·react native·react.js·harmonyos
2601_9498333914 分钟前
flutter_for_openharmony口腔护理app实战+饮食记录实现
android·javascript·flutter
2601_9494800623 分钟前
【无标题】
开发语言·前端·javascript
css趣多多28 分钟前
Vue过滤器
前端·javascript·vue.js
理人综艺好会1 小时前
Web学习之用户认证
前端·学习
●VON1 小时前
React Native for OpenHarmony:项目目录结构与跨平台构建流程详解
javascript·学习·react native·react.js·架构·跨平台·von
We་ct1 小时前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
爱吃大芒果1 小时前
Flutter for OpenHarmony 实战:mango_shop 路由系统的配置与页面跳转逻辑
开发语言·javascript·flutter
qq_177767371 小时前
React Native鸿蒙跨平台实现消息列表用于存储所有消息数据,筛选状态用于控制消息筛选结果
javascript·react native·react.js·ecmascript·harmonyos