在辅助方法中反应 i18next useTranslation Hook

React i18next useTranslation Hook in helper method

我正在使用 React 和 react-i18next

我的 index.tsx 文件包含一些组件,我可以在那里使用翻译功能

index.js
import React, { Suspense } from 'react'
import ReactDOM from 'react-dom';
import * as utils from './Utils';
import './i18n';
import { useTranslation, withTranslation, Trans } from 'react-i18next';

...
  const { t, i18n } = useTranslation();
  //I can use the translate function here
  t("title");
  //call a util function
  utils.helperFunction(...);
...

这里一切正常。 我现在在附加文件中创建了一些辅助函数

Utils.tsx
...
import { useTranslation, withTranslation, Trans } from 'react-i18next';
...
export function helperFunction(props: any){
   //do stuff

   //now I need some translation here - but useTranslation is not working?
   const { t, i18n } = useTranslation();
   t("needTranslation");
}

如何在我的辅助函数中使用相同的翻译逻辑? (不总是将 t 函数传递给辅助方法)

或者这里使用 hook 是错误的方法吗?

出现如下错误

React Hook "useTranslation" is called in function "helperFunction" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

你好像忘了引用 t("needTranslation); -> t("needTranslation");

在我 运行 你的代码之后,我明白了为什么你的代码不起作用。如果你想将组件逻辑提取到可重用的函数中,那么你应该制作一个自定义钩子。有关更多信息,请查看 docs.

import React from "react";
import ReactDOM from "react-dom";
import i18n from "i18next";
import "./i18n.js";
import { useTranslation, initReactI18next } from "react-i18next";

i18n
  .use(initReactI18next) 
  .init({
    resources: {
      en: {
        translation: {
          title: "Hello world",
          subtitle: "Hello Whosebug"
        }
      }
    },
    lng: "en",
    fallbackLng: "en",

    interpolation: {
      escapeValue: false
    }
  });

function App() {
  const { t } = useTranslation();
  useHelperFunction();
  return <h1>{t("title")}</h1>;
}

// you need to turn the helper function into a hook
function useHelperFunction() {
  const { t } = useTranslation();
  return <h2>{t("subtitle")}</h2>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我不再使用 useTranslation 挂钩解决了我的问题

相反,我将 i18n 初始化移动到一个文件中(i18n.tsx - 导出 i18n) 并在我的 Utils class

中导入并使用它

我的 Utils.tsx 文件现在看起来像这样

Utils.tsx

...
import i18n from '../i18n';
...
export function helperFunction(props: any){
   //do stuff

   //use imported i18n and call the t() method
   i18n.t("needTranslation");
}

i18n.tsx

import i18n from "i18next";
import Backend from 'i18next-xhr-backend';
import { initReactI18next } from 'react-i18next';

i18n
  .use(Backend) 
  .use(initReactI18next) // passes i18n down to react-i18next
  .init({
    lng: "es",
    fallbackLng: 'en',
    backend: {
      loadPath: '/static/locales/{{lng}}/{{ns}}.json'
    },    
    interpolation: {
      escapeValue: false
    }
  });

  export default i18n;