How to use setLocale within i18n-js?

前端 未结 1 1884
走了就别回头了
走了就别回头了 2021-01-25 09:37

I am using i18n-js within my expo project to translate my app.

This is how I configure it:

import React from \'re         


        
1条回答
  •  -上瘾入骨i
    2021-01-25 09:47

    You need to setup the translation in your top level component, like App.js. Then, you have to create 2 json files: fr.json and en.json in /src/locales/.

    Finally, in any screen, you have to import i18n and use the t() function to translate strings.

    In 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 (
        
      )
    }
    

    In 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
    

    In HomeView.js

    import React from 'react'
    import i18n from '../locales/i18n'
    
    function HomeScreen({ navigation }) {
    
      return (
        
          {i18n.t('home.welcome')}
          {i18n.t('home.content')}
        
      )
    }
    
    export default HomeView
    

    In fr.json

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

    0 讨论(0)
提交回复
热议问题