项目地址:https://github.com/AlexanderZaytsev/react-native-i18n
使用方式:
使用yarn:yarn add react-native-i18n;
使用npm:npm install react-native-i18n --save;
0.60版本以下记得手动link
react-native link react-native-i18n
以下内容可能比较跳跃,本篇主要是记录一下遇到的异常及暂时的解决方式。
页面调用:
import I18n from "../../language/I18n";
<Text style={styles.itemTxt}>{I18n.t('timer_control')}</Text>
下面进行了一些预设,默认语言为en,fallbacks为true,依次遍历向下翻译。
I18n.locale方法在默认获取时 获得到的是手机系统的语言与地区
如果需要做语言设置的持久化存储还请注意流程上先读取到持久化存储中的语言设置并设置给I18n。
I18n.defaultLocale = 'en';
I18n.fallbacks = true;
I18n.translations = {
en,
zh,
};
I18n.localeLanguage = () => {
console.log('localLanguage start;',I18n.locale);
new DataRepository().fetchLocalRepository('localLanguage')
.then((res)=>{
if (res==null){
// res='en'
}else {
I18n.locale = res;
}
console.log('localLanguage;',I18n.locale);
// console.log('localLanguage;','res');
// RCTDeviceEventEmitter.emit('setLanguage', index);
})
.catch((error)=>{
I18n.locale = 'en-US';
});
return I18n.locale;
};
这个过程可能耗时几十毫秒 ,如果在这个过程中 加载了第一个界面,那么第一个界面绘制时拿到的
语言版本会与手机本地一致,需要再次刷新后才能与持久化存储的语言版本一致。假设有启动页的情况下是可以较好的避开这个问题,因为当前项目并无启动页所以我在此处是设置了第一个界面绘制时延时100毫秒重绘一次,如果有更好的方式希望大家评论区留给我。