【问题标题】:How to use setLocale within i18n-js?如何在 i18n-js 中使用 setLocale?
【发布时间】:2020-05-13 22:13:10
【问题描述】:

我在我的 expo 项目中使用 i18n-js 来翻译我的应用程序。

这是我的配置方式:

import React from 'react';
import * as Localization from 'expo-localization';
import i18n from 'i18n-js';

export default function configureI18n(translations) {
  i18n.fallbacks = true;
  i18n.translations = translations;
  i18n.locale = Localization.locale;
  const [locale, setLocale] = React.useState(Localization.locale);
  const localizationContext = React.useMemo(() => ({
    t: (scope, options) => i18n.t(scope, { locale, ...options }),
    locale,
    setLocale,
  }), [locale]);

  return localizationContext;
}

我将此传递给我的AppContext 并尝试在我的视图中使用setLocale

function HomeView(props) {
  const { locale, setLocale } = useContext(AppContext);

  return (
    <View>
            <Button
              style={{ marginTop: 4 }}
              icon="translate"
              mode="contained"
              title="toggle navigation"
              onPress={() => setLocale(locale.includes('en') ? 'fr' : 'en')}
            >
              {locale.includes('en') ? 'FR' : 'EN'}
            </Button>
    </View>
  );
}

调用了函数,但文字还是英文,我做错了什么?

【问题讨论】:

    标签: javascript reactjs react-native expo i18n-js


    【解决方案1】:

    您需要在顶级组件中设置翻译,例如 App.js。然后,您必须在/src/locales/ 中创建2 个json 文件:fr.jsonen.json

    最后,在任何屏幕中,您都必须导入i18n 并使用t() 函数来翻译字符串。

    在 App.js 中

    import React, { useEffect, useState } from 'react'
    import { loadLocale } from './locales/i18n'
    
    export default function App() {
      const [theme, setTheme] = useState(null)
    
      useEffect(() => {
        init()
      }, [])
    
      const init = async () => {
        await loadLocale()
      }
    
      return (
        <AppContainer />
      )
    }
    

    在 i18n.js 中

    import * as Localization from 'expo-localization'
    import i18n from 'i18n-js'
    
    i18n.defaultLocale = 'fr'
    i18n.locale = 'fr'
    i18n.fallbacks = true
    
    export const loadLocale = async () => {
      for (const locale of Localization.locales) {
        if (i18n.translations[locale.languageCode] !== null) {
          i18n.locale = locale.languageCode
          switch (locale.languageCode) {
            case 'en':
              import('./en.json').then(en => {
                i18n.translations = { en }
              })
              break
            default:
            case 'fr':
              import('./fr.json').then(fr => {
                i18n.translations = { fr }
              })
              break
          }
          break
        }
      }
    }
    
    export default i18n
    

    在 HomeView.js 中

    import React from 'react'
    import i18n from '../locales/i18n'
    
    function HomeScreen({ navigation }) {
    
      return (
        <View style={{ flex: 1 }}>
          <Text>{i18n.t('home.welcome')}</Text>
          <Text>{i18n.t('home.content')}</Text>
        </View>
      )
    }
    
    export default HomeView
    

    在 fr.json 中

    {
      "home": {
        "welcome": "Bienvenue",
        "content": "Du contenu ici"
      }
    }
    

    【讨论】:

    • 嗨@Mback,非常有趣的回复。我想异步加载我的字体,但我从来不知道import('./fr.json').then(...) 是加载组件的有效异步合成器。它像在网络中一样工作吗?它会创建一个块吗?我想我可以用这个来优化我的应用程序。在react-nativereact-native-web环境中使用安全吗?
    • 它在react-native 中运行良好,因为我在我的应用程序中使用它。在react-native-web 我不知道,也许。我只知道如果您使用 Next.js,处理动态导入非常简单
    • @Mach 切换语言后一段时间返回[缺少“en.appname”翻译]
    【解决方案2】:

    为了在语言之间切换并避免出现 [missing "X.string" translation] 错误,您可以在下面添加一个类似“changeLanguage”函数的函数:

    // Imagine you have spanish and english languages support
    import es from './locales/es';
    import en from './locales/en';
    const availableTranslations = {
        es,
        en
    };
    
    /* This function is useful to load spanish or english language translations and set the corresponding locale */
    const changeLanguage = (languageCode) => {
        I18n.translations = {
            [languageCode]: availableTranslations[languageCode]
        };
        I18n.locale = languageCode;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-18
      • 2022-12-03
      • 2021-12-09
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      相关资源
      最近更新 更多