如何在 BASIC 函数(非组件)中使用 react-i18next?

The*_*tti 1 react-i18next

我知道 react-i18next 在每个组件中都可以工作:函数式(使用 useTranslation)和类组件(使用 withTranslation())但是我不能在这样的基本函数中使用翻译:

const not_a_component = () => {
  const { t } = useTranslation();
  return t('translation')
};

const translate = not_a_component();
Run Code Online (Sandbox Code Playgroud)

错误钩子!

谢谢 !

tar*_*ugh 7

您可以使用i18next库来使用 javascript 进行翻译。 react-i18next只是i18next.

下面是一个示例,如果您已经在使用react-i18next并且已配置它。

import i18next from "i18next";

const not_a_component = () => {
  const result = i18next.t("key");
  console.log(result);
  return result;
};

export default not_a_component;
Run Code Online (Sandbox Code Playgroud)

如果您选择仅使用,i18next那么您可以简单地获取t功能。这一切都取决于您的要求。

import i18next from 'i18next';

i18next.init({
  lng: 'en',
  debug: true,
  resources: {
    en: {
      translation: {
        "key": "hello world"
      }
    }
  }
}, function(err, t) {
  // You get the `t` function here.
  document.getElementById('output').innerHTML = i18next.t('key');
});
Run Code Online (Sandbox Code Playgroud)

希望有帮助!!!


wea*_*ish 5

或者,您可以t作为附加参数传递:

const not_a_component = (t) => {
  return t('translation')
};

// Within a component
const { t } = useTranslation()
not_a_component(t)
Run Code Online (Sandbox Code Playgroud)