react(Taro)使用i18n国际化

本文介绍如何使用i18next等工具实现应用的多语言支持,包括安装依赖、配置语言文件及在React应用中应用国际化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下载依赖

npm install react-i18next i18next i18next-browser-languagedetector

新建文件,配置

// 新建index.jsx
import LanguageDetector from 'i18next-browser-languagedetector';
import i18n from "i18next";
import zh from './zh'
import en from './en'
// eslint-disable-next-line import/first
import {initReactI18next} from 'react-i18next';

i18n.use(LanguageDetector) //嗅探当前浏览器语言
.use(initReactI18next) //init i18next
.init({
  //引入资源文件
  resources: {
    en: {
      translation: en,
    },
    zh: {
      translation: zh,
    },
  },
  //选择默认语言,选择内容为上述配置中的key,即en/zh
  lng: 'zh',
  debug: false,
  interpolation: {
    escapeValue: false, // not needed for react as it escapes by default
  },
})

export default i18n;


// 新建zh.js
export default {
    home : '主页',
    welcome : '欢迎来到主页'
}

// 新建en.js
export default {
    home : 'Home',
    welcome : 'Welcome to home page'
}
// app.jsx下
/* eslint-disable import/first */
import React, { Component } from 'react'
import { Provider } from 'mobx-react'
import http from './utils/http'
import 'taro-ui/dist/style/index.scss'

import globalStore from './store/counter'

import CommenJS from './utils/commen'

import i18n from './i18n/index'  //引入


import './app.scss'

const store = {
  globalStore
}

Component.prototype.$http = http;
Component.prototype.$i18n = i18n  //封装到全局
CommenJS(Component)

class App extends Component {
  componentDidMount () {}

  componentDidShow () {}

  componentDidHide () {}

  componentDidCatchError () {}

  // this.props.children 就是要渲染的页面
  render () {
    return (
      <Provider store={store}>
        {this.props.children}
      </Provider>
    )
  }
}

export default App

页面使用/改变语言

// 使用
import { Translation } from 'react-i18next'

<Translation>
     {
          t => <Text>{t('home')}</Text>
     }
</Translation>


// 改变语言
changeLang(){
   this.$i18n.changeLanguage('en') // 'en' 'zh'等等
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值