首页 > 解决方案 > 如何在 i18n-js 中使用 setLocale?

问题描述

我在我的 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>
  );
}

该函数被调用,但文本仍然是英文,我做错了什么?

标签: javascriptreactjsreact-nativeexpoi18n-js

解决方案


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

最后,在任何屏幕中,您都必须导入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"
  }
}

推荐阅读