react native 国际化

react-i18next 和 i18n,运用高级组件的形式。

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import zh from './translation/zh.json';

import en from './translation/en.json'

import tw from './translation/tw.json';
// 语言资源 缓存
const languageResources ={};

// 异步获取翻译资源的函数
const fetchTranslations = async (lng) => {
  try {
    return new Promise((resolve) => {
      if (languageResources[lng]) {
        resolve(languageResources[lng]);
      }
      setTimeout(() => {
        if(lng =="zh"){
          resolve(zh);
        }else if(lng =="en"){
          resolve(en);
        }else if(lng =="tw"){
          resolve(tw);
        }
        
      }, 1000*8);
    })

  
    
  } catch (error) {
    languageResources.zh=zh;
    languageResources.en=en;
    languageResources.tw=tw;
  }
};

const initI18n = async () => {
   // 并行加载所有语言资源
   const [zhResources, enResources, twResources] = await Promise.all([
    fetchTranslations('zh'),
    fetchTranslations('en'),
    fetchTranslations('tw')
  ]);
  
  languageResources.zh = zhResources;
  languageResources.en = enResources;
  languageResources.tw = twResources;
  i18n
  .use(initReactI18next) // 将 i18next 与 react-i18next 结合
  .init({
    compatibilityJSON: 'v3', // 对安卓进行兼容
    resources: {
      zh: {
        translation: languageResources.zh, // 中文简体翻译
      },
      en: { //英语
        translation: languageResources.en
      },
      'zh-tw': { // 繁體中文
        translation: languageResources.tw
      },
      initImmediate: false // 确保完全初始化
    },
    lng: 'zh', // 默认语言
    fallbackLng: 'zh', // 如果当前语言没有对应的翻译,则使用默认语言
    interpolation: {
      escapeValue: false, // React 已经处理了转义
    },
  }, (err, t) => {
    // 錯誤
    if (err) throw err;
    // 这里放多一层函数是为了方便之后切换语言的同时做一些其他的统一处理
    i18n.setLocalLanguage = function (value) {
      // 設置項目文本的語言
      // this.changeLanguage(value);
      // 做点别的,比如同时切换别的插件的语言
    }
    // 初始化
    i18n.setLocalLanguage(i18n.language);

  });

  console.log("i18n========国际化初始化完成", i18n)
  return i18n

}




export default initI18n;

未加载成功,的提示信息。

// withLoading.js
import React from 'react';
import { View, Text, ActivityIndicator, StyleSheet } from 'react-native';
import initI18n from './i18n';
const withLoading = (WrappedComponent) => {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        i18nLoaded: false,
        i18nError: false
      };
    }

    async componentDidMount() {
      try {
        // 等待i18n初始化完成
        // console.log("initI18n",initI18n)
        console.log("this.props======",this.props)
        let a = await initI18n();
        // console.log(a,"======withLoading======")
    
        this.setState({ i18nLoaded: true });
      } catch (error) {
        console.error('初始化i18n失败:', error);
        this.setState({ i18nError: true });
      }
    }

    render() {
      const { i18nLoaded, i18nError } = this.state;

      if (i18nError) {
        return (
          <View style={styles.center}>
            <Text>Initialization failed, please check the network</Text>
          </View>
        );
      }

      if (!i18nLoaded) {
        return (
          <View style={styles.center}>
            <ActivityIndicator size="large" color="#0000ff" />
            <Text style={{marginTop:20}}>Initializing...</Text>
          </View>
        );
      }

      return <WrappedComponent {...this.props} />;
    }
  };
};

const styles = StyleSheet.create({
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default withLoading;

在根目录文件引用

import './locales/i18n';
import withLoading from './locales/withLoading';
import { withTranslation } from 'react-i18next';

//高级组件的导入

export default withLoading(withTranslation()(withTheme(App)));

更多推荐