我在react-native中的应用程序有2种语言:英语和法语。我已经完成了一个i18n.js文件和2个针对英语和法语的“ translation.js”文件。效果很好(我尝试过在手机上设置法语,在模拟器上设置英语)。
现在,我想在应用程序设置中创建一个按钮,以为用户更改整个应用程序的语言,但是我不知道调用什么函数以及如何创建该函数。
您能帮我吗?非常感谢您的时间和帮助。
我的i18n.js文件;
import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";
import { NativeModules, Platform } from "react-native";
import en from "../public/locales/en/translation.js";
import fr from "../public/locales/fr/translation.js";
// the translations
const resources = {
en: {
translation: en
},
fr: {
translation: fr
}
};
const locale =
Platform.OS === "ios"
? NativeModules.SettingsManager.settings.AppleLocale
: NativeModules.I18nManager.localeIdentifier;
i18n.locale = locale;
i18n
.use(detector)
.use(reactI18nextModule) // passes i18n down to react-i18next
.init({
resources,
lng: locale.substring(0, 2),
fallbackLng: "en", // use en if detected lng is not available
keySeparator: ".", // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
而且我想从我的Settings.js文件中更改语言:
<SettingsList.Item
// icon={<Image style={styles.image} source={require('../../assets/images/icon_vol-mute.png')}/>}
title={i18n.t("settings.action.languages")}
hasNavArrow={false}
switchState={this.state.activeSwitch === 3}
switchOnValueChange={this.switchThree}
hasSwitch={true}
onPress={() => Alert.alert("French / English")}
/>
在通常情况下。有两种方法可以实现您的目的。
使用react-native-i18n和react-native-localization
但是我建议react-native-localization
和simply in implementation
推荐native performance
react-native-localization
?yarn add react-native-localization --save
#react-native >= 0.60
cd ios && pod install && cd ..
#react-native < 0.60
react-native link react-native-localization
import LocalizedStrings from 'react-native-localization';
import english from './en.js'
import french from './fr.js'
import korean from './kr.js'
const strings = new LocalizedStrings({
en: english,
fr: french,
kr: korean,
});
带有en.js
,fr.js
,kr.js
的文件包含您以key
value
格式进行的翻译。
例如:fr.js
的内容
export default {
ok: 'D'accord',
no: 'non'
}
您也可以使用json
文件类型进行声明。
import strings from 'services/translation';
<Text style={styles.title}>
{strings.ok}
</Text>
编写一个功能来更改您的应用语言,并在您需要的任何地方使用它。
const strings = new LocalizedStrings({
en: english,
fr: french,
kr: korean,
});
export const changeLaguage = (languageKey) => {
strings.setLanguage(languageKey)
}
import { changeLaguage } from 'services/translation'
<Button onPress={() => {changeLanguage(languageKey)}} />
查看有关注意:不要在默认方法,例如
setLanguage
中声明相同的键
react-native-localization
here的更多信息