【问题标题】:How to set the default language in i18next - React Native?如何在 i18next - React Native 中设置默认语言?
【发布时间】:2021-06-28 09:44:27
【问题描述】:

当用户第一次打开应用程序时,我正在尝试设置默认语言,我正在使用 i18next 和 react-i18next 我想要的默认语言是ar, 有没有办法在没有用户操作的情况下做到这一点,比如将语言更改为ar 的按钮?

这是我的配置

import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import {I18nManager} from 'react-native';
// the translations
const ar = require('./Lang/ar.json');
const en = require('./Lang/en.json');

const resources = {
  en: {
    translation: en,
  },
  ar: {
    translation: ar,
  },
};

i18n.use(initReactI18next).init({
  resources,
  lng: I18nManager.isRTL ? 'ar' : 'en',
  fallbackLng: 'ar',
  keySeparator: false,
  interpolation: {
    escapeValue: false,
  },
});

export default i18n;

【问题讨论】:

    标签: javascript reactjs react-native i18next react-i18next


    【解决方案1】:

    在您的 App.js 中,检查当前用户语言以确定语言:

    import i18next from 'i18next';
    import { initReactI18next } from 'react-i18next';
    
    const languageDetector = {
      type: 'languageDetector',
      async: true,
      detect: cb => {
        const deviceLanguage =
            Platform.OS === 'ios'
              ? NativeModules.SettingsManager.settings.AppleLocale ||
                NativeModules.SettingsManager.settings.AppleLanguages[0] // iOS 13
              : NativeModules.I18nManager.localeIdentifier;
          cb(deviceLanguage.indexOf('vi')>=0?'vi':'en')
      },
      init: () => {},
      cacheUserLanguage: () => {},
    };
    
    i18next
      .use(languageDetector)
      .use(initReactI18next)
      .init({
        fallbackLng: 'en',
        debug: false,
        resources: languages,
      });
    function App(){ return ....}
    

    【讨论】:

    • 这将获得用户移动语言,如果它不是我们想要的默认语言,我们将应用用户移动语言,但无论用户移动语言如何,我都需要在第一次强制用户使用默认语言跨度>
    • 简单的回调检测,无需检查即可通过您的语言
    【解决方案2】:

    试试这个:

    import { reactI18nextModule } from 'react-i18next';
    const ar = require('./Lang/ar.json');
    const en = require('./Lang/en.json');
    
    i18n.use(reactI18nextModule).init({
      resources: {
        ar,
        en,
      },
      fallbackLng: 'ar',
      keySeparator: false,
      interpolation: {
        escapeValue: false,
      },
    });
    

    提示

    最好将 fallback-lang 又名默认语言作为用户设备语言,而不是将其硬编码为 ar ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 2016-12-25
      相关资源
      最近更新 更多