基于 react-native-localize、 i18n-js两个包做国际化,先添加:
yarn add react-native-localize
yarn add i18n-js
ios要 cd ios & pod install 一下,
添加中文、英文的国际化文件:
en.js:
export default {
hello: "Hello"
};
zh.js:
export default {
hello: "你好"
};
I18n.js(国际化配置):
import I18n from "i18n-js";
import * as RNLocalize from "react-native-localize";
import en from "./locales/en";
import zh from "./locales/zh";
// 获取本机语言
const locales = RNLocalize.getLocales();
if (Array.isArray(locales)) {
// 取第一个做默认语言
I18n.locale = locales[0].languageTag;
}
I18n.fallbacks = true;
I18n.translations = {
en,
zh
};
I18n.changeLanguage = language => {
I18n.locale = language;
}
export default I18n;
App.js:
import React from 'react';
import I18n from "./src/utils/I18n";
import {SafeAreaView, Text, View,} from 'react-native';
import {Colors} from "react-native/Libraries/NewAppScreen";
const AppData = () => {
const backgroundStyle = {
backgroundColor: Colors.light,
};
return (
<SafeAreaView style={backgroundStyle}>
<View style={{
height: '100%',
width: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>
{I18n.t("hello")}
</Text>
</View>
</SafeAreaView>
)
}
const App2 = () => {
return (
<AppData/>
)
}
export default App2;
参考:https://medium.com/@nicolas.kovacs/react-native-localize-and-i18n-js-117f09428017