[英]How to get current locale with i18next / react-i18next?
我是 react-native 的新手,我正在嘗試從用戶的設備獲取當前語言環境。 目前,我的應用程序有 2 個版本:法語和英語。 當我更改后備語言時它工作正常,我確實有兩個版本的應用程序。 但我無法直接從設備更改語言。
我們可以手動更改,但如果我們在設備上設置了法語,則無法直接獲取法語。
import i18next from 'i18next';
import {initReactI18next} from 'react-i18next';
const languageDetector = {
type: 'languageDetector',
async: true,
detect: cb => cb('en'),
init: () => {},
cacheUserLanguage: () => {},
};
i18next
.use(languageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
debug: true,
resources: {
en: {
translation: {
hello: 'Hello world',
change: 'Change language',
},
},
sv: {
translation: {
hello: 'Hallo!',
change: 'Goedemorgen',
},
},
},
});
export default i18next;
應用程序.js
import React from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import { useTranslation } from 'react-i18next';
import './src/Traslations'
export default function App() {
const { t, i18n } = useTranslation();
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 20, marginBottom: 20 }}>{t('hello')}</Text>
<Text style={{ fontSize: 20, marginBottom: 20 }}>{t('change')}</Text>
<TouchableOpacity style={{backgroundColor: 'pink'}} onPress={() => i18n.changeLanguage(i18n.language === 'nl' ? 'en' : 'nl')}>
<Text>{t('change')}</Text>
</TouchableOpacity>
</View>
);
}
您的languageDetector
使用en
作為fallback
語言...
確保您在設備中選擇的語言前綴是sv
<<-- 您在i18n
設置中擁有的密鑰...
const languageDetector = {
type: 'languageDetector',
async: true,
detect: cb => cb('en'), // <<---- here
init: () => {},
cacheUserLanguage: () => {},
};
反而
你想通過 current-device-lang
import { Platform, NativeModules, Dimensions } from 'react-native';
const getDeviceLang = () => {
const appLanguage =
Platform.OS === 'ios'
? NativeModules.SettingsManager.settings.AppleLocale ||
NativeModules.SettingsManager.settings.AppleLanguages[0]
: NativeModules.I18nManager.localeIdentifier;
return appLanguage.search(/-|_/g) !== -1
? appLanguage.slice(0, 2)
: appLanguage;
};
detect: async callback => {
const deviceLang = getDeviceLang();
callback(appLanguage);
},
更多細節可以在這里找到一個工作樣本......
i18next.language或i18next.languages可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.