当使用useTranslation()中的t()时,会反应i18next的“挂钩”错误

时间:2019-03-15 13:08:11

标签: reactjs internationalization i18next react-i18next

我正在使用React-i18next库,我需要在函数内部获取翻译函数t()

export function translateCell(cell) {
  const { t } = useTranslation();
  return (t(cell));
}

使用useTranslation()时失败,并显示错误

  

只能在函数组件的主体内部调用钩子。

我尝试在初始化时使用I18nextProvider以及.use(initReactI18next),但是两种设置都会产生相同的错误。

我使用方式错误吗?还是我误解了某些东西?

编辑: 我发现,只有将作为组件呈现的函数才能使用useTranslation。像

function export MyComponent (cell) {
  const { t } = useTranslation();
  return (<div>{t(cell)}</div>);
}
...
render(){
<MyComponent/>

2 个答案:

答案 0 :(得分:0)

我发现在初始化后导出i18n对象的解决方案,并将其用于我需要的所有其他地方。

文件i18nSetup.js

i18n
    .use(initReactI18next)
    .init({
        resources: translationResources,
        interpolation: {
            escapeValue: false 
        }
    });

export default i18n;

在其他文件中

import i18n from "../functions/i18nSetup";

export function translateCell(cell) {
  return (i18n.t(cell));
}

答案 1 :(得分:0)

试试这个:

import { Trans } from 'react-i18next';

并像这样使用它:

<Trans>word-key</Trans>

https://react.i18next.com/guides/quick-start