i18next 和 react-i18next 是用于实现国际化(i18n)的库。它们结合起来为 React 应用程序提供了一个强大的多语言支持解决方案。
安装:
npm install i18next react-i18next
配置en.json
{
"hello": "hello",
"world": "world"
}
配置zhC.json
{
"hello":"你好",
"world": "世界"
}
配置languages.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// 语言包
import en from './en.json'
import zh from './zhCN.json'
const resources = {
en: {
translation: en
},
zh: {
translation: zh
}
}
i18n
.use(initReactI18next)
.init({
compatibilityJSON: 'v3', // 对安卓进行兼容
resources,
fallbackLng: 'zh', // 默认语言,也是设置语言时设置了不存在的语言时使用的
interpolation: {
escapeValue: false
}
}, (err) => {
// 錯誤
if (err) throw err;
// 这里放多一层函数是为了方便之后切换语言的同时做一些其他的统一处理
i18n.setLocalLanguage = function (value) {
// 設置項目文本的語言
this.changeLanguage(value);
// 做点别的,比如同时切换别的插件的语言
}
// 初始化
i18n.setLocalLanguage(i18n.language);
});
export default i18n;
在根目录index.js引入 languages.js
类组件中使用
import React, { Component } from "react";
import { View, Text, Button } from "react-native";
import { withTranslation } from 'react-i18next';
class HomeScreen extends Component {
render() {
const { t, i18n } = this.props;
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>当前语言包:{i18n.language}</Text>
<Text>{i18n.t("请输入您的手机号")}{i18n.t("")}</Text>
<Button title='切换为中文' onPress={() => i18n.changeLanguage('zh')}></Button>
<Button title='切换为英文' onPress={() => i18n.changeLanguage('en')}></Button>
</View>
);
}
}
export default withTranslation()(HomeScreen);
函数组件中使用
import React from "react";
import { View, Text, Button } from "react-native";
import { useTranslation } from 'react-i18next'
const HomeScreen = (props) => {
// 拿到i18n
const { i18n } = useTranslation();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>当前语言包:{i18n.language}</Text>
<Text>{i18n.t("hello")}{i18n.t("world")}</Text>
<Button title='切换为中文' onPress={() => i18n.changeLanguage('zh')}></Button>
<Button title='切换为英文' onPress={() => i18n.changeLanguage('en')}></Button>
</View>
);
};
export default HomeScreen;