useTranslation 在 React/TypeScript 中不起作用。

huangapple go评论71阅读模式
英文:

useTranslation not working in react/typescript

问题

I have a project write with react/typescript and I want to change language. I use i18n but when I use useTranslation to change language it doesn't work.

packages:

"i18next": "22.4.9",
"react-i18next": "12.1.4"

i18n -> config.js

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

i18n.use(initReactI18next).init({
  fallbackLng: 'en',
  lng: 'en',
  resources: {
    en: {
      translations: require('./locales/en/translations.json')
    }
  },
  ns: ['translations'],
  defaultNS: 'translations'
});

i18n.languages = ['en'];

export default i18n;

i18n -> locales -> en -> translations.json

{    
    "errorMessage": "Please try again later."
}

App.tsx

import { useTranslation } from 'react-i18next';

const App = () => {

    const { t } = useTranslation();

    return (<>
        {t('errorMessage')}
    </>)
}

export default App

On running, I see this:

errorMessage

instead of

Please try again later.

What am I missing?

英文:

I have a project write with react/typescript and I want to change language. I use i18n but when i use useTranslation to change language it doesn't work.

packages:

&quot;i18next&quot;: &quot;22.4.9&quot;,
&quot;react-i18next&quot;: &quot;12.1.4&quot;

i18n -> config.js

import i18n from &#39;i18next&#39;;
import { initReactI18next } from &#39;react-i18next&#39;;

i18n.use(initReactI18next).init({
  fallbackLng: &#39;en&#39;,
  lng: &#39;en&#39;,
  resources: {
    en: {
      translations: require(&#39;./locales/en/translations.json&#39;)
    }
  },
  ns: [&#39;translations&#39;],
  defaultNS: &#39;translations&#39;
});

i18n.languages = [&#39;en&#39;];

export default i18n;

i18n -> locales -> en -> translations.json

{    
    &quot;errorMessage&quot;: &quot;Please try again later.&quot;
}

App.tsx

import { useTranslation } from &#39;react-i18next&#39;;

const App = () =&gt; {

    const { t } = useTranslation();

    return (&lt;&gt;
        {t(&#39;errorMessage&#39;)}
    &lt;/&gt;)
}

export default App

On running, I see this:

> errorMessage

instead of

> Please try again later.

What am I missing?

答案1

得分: 1

You have to import the config.js file preferably in App.tsx file since it has to be bundled.

import &#39;./i18n/config&#39;;
英文:

You have to import the config.js file preferably in App.tsx file since it has to be bundled.

import &#39;./i18n/config&#39;;

huangapple
  • 本文由 发表于 2023年4月20日 06:55:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059378.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定