react(Taro)使用i18n国际化
·
下载依赖
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'等等
}
更多推荐
所有评论(0)