61 lines
1.6 KiB
JavaScript
61 lines
1.6 KiB
JavaScript
import i18n from 'i18next';
|
|
import { initReactI18next } from 'react-i18next';
|
|
import * as RNLocalize from 'react-native-localize';
|
|
import AsyncStorage from '@/storage/index';
|
|
// 导入语言包
|
|
import en from './en.json';
|
|
import zh from './zh.json';
|
|
console.log('🚀 ~ RNLocalize:', RNLocalize)
|
|
|
|
// 导入语言资源
|
|
const resources = {
|
|
en: { translation: en },
|
|
zh: { translation: zh }
|
|
};
|
|
|
|
const languageDetector = {
|
|
type: 'languageDetector',
|
|
async: true,
|
|
detect: async callback => {
|
|
try {
|
|
// 从本地存储读取用户选择的语言
|
|
const saveLng = await AsyncStorage.getItemAsync('@APP_LANGUAGE');
|
|
const lng = saveLng ? saveLng.lng : null;
|
|
|
|
// 如果没有选择的语言,使用设备首选语言
|
|
const bestLanguageOption = RNLocalize.getLocales()[0].languageCode || 'en';
|
|
callback(lng || bestLanguageOption);
|
|
} catch (error) {
|
|
console.error("Failed to detect or load the language", error);
|
|
}
|
|
},
|
|
init: () => {},
|
|
cacheUserLanguage: async lng => {
|
|
console.log('🚀 ~ lng:', lng)
|
|
try {
|
|
// 将用户选择的语言存储到本地
|
|
await AsyncStorage.setItemAsync('@APP_LANGUAGE', {lng});
|
|
} catch (error) {
|
|
console.error("Failed to save the user's language choice", error);
|
|
}
|
|
},
|
|
};
|
|
|
|
|
|
i18n
|
|
.use(languageDetector)
|
|
.use(initReactI18next)
|
|
.init({
|
|
resources,
|
|
fallbackLng: 'en',
|
|
compatibilityJSON: 'v3',
|
|
interpolation: {
|
|
escapeValue: false, // react already saves from xss
|
|
},
|
|
});
|
|
|
|
export default i18n;
|
|
|
|
|
|
|