源码见文尾
),废话很少说开始正题。
yarn add react-native-i18n
yarn add react-native-device-info
and react-native link react-native-device-info
在项目中建立zh.js
、en.js
、I18n.js
三个js文件,DataRepository.js
是一个我自定义的数据持久化类,在这个demo中的做用是存取用户改变后的语言环境,直接拷贝过去就能够用(不是必须的)。 react
zh.js
export default {
english: '英文',
chinese: '中文',
changeToEnglish: '切换到英文',
changeToChinese: '切换到中文',
changeToSystem: '切换到系统语言',
}
复制代码
en.js
ios
export default {
english: 'english',
chinese: 'chinese',
changeToEnglish: 'change to english',
changeToChinese: 'change to chinese',
changeToSystem: 'change to System',
}
复制代码
I18n.js
git
import I18n,{ getLanguages } from 'react-native-i18n'
import DeviceInfo from 'react-native-device-info'
import DataRepository from '../dao/DataRepository'
import en from './en'
import zh from './zh'
I18n.defaultLocale = 'en';
I18n.fallbacks = true;
I18n.translations = {
en,
zh,
};
I18n.localeLanguage = () => {
new DataRepository().fetchLocalRepository('localLanguage')
.then((res)=>{
I18n.locale = res;
})
.catch((error)=>{
I18n.locale = DeviceInfo.getDeviceLocale();
});
return I18n.locale;
};
export { I18n, getLanguages };
复制代码
I18n.t()
: 使用频率是最高的,举个栗子:<Text style={styles.welcome}>
{I18n.t('english')}
</Text>
复制代码
以上I18n.t('english')
中的english
参数就是在zh.js
、en.js
文件中的语言配置项 github
I18n.getLanguages
获取用户首选的语言环境I18n.locale
: 设置本地语言环境。I18n.defaultLocale
首选默认语言I18n.fallbacks
: 看文档说明我理解的意思是:若是获取到的系统语言相似en_US
en-GB
这样的,插件初始化的时候发现没有en_US.js
en-GB.js
,这个时候若是设置了I18n.fallbacks = true;
系统就会按这样的(en_US
en.js
)顺序去查找文件,就会去找有一个en.js
这样的文件, 官方建议使用I18n.fallbacks = true;
i18n-js
的属性和方法请 点击这里查看我在使用过程当中发现调用了I18n.locale=‘我设置的语言’
后,当前的界面语言并无改变,而其余界面的语言已经改变了,就好比说我上面截图的侧滑菜单,当我在侧滑菜单切换语言后发现侧滑菜单里面的语言并无发现变化,而首页的语言环境已经改变了,我不知道为何,摸索最后找到了一种解决方案(可能不是最佳方案,可是解决了刷新当前界面语言的问题,若是有更好的方法欢迎👏分享),解决方案:调用一下setState
(不管设置的这个state
属性在render
中有没有被使用,都有效)。 具体代码看App.js
,我项目中有使用localeLanguage
因此我把改变后的语言存到state
中react-native
this.setState({
localeLanguage: I18n.locale
});
复制代码
demo 在此 ,本次写做到此,欢迎❤️⭐️👏指出错误或者发布本身的看法探讨,共勉。🤝bash