4

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

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

const translate = not_a_component();

错误挂钩!

谢谢 !

4

2 回答 2

13

您可以使用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;

如果您选择仅使用,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');
});

希望有帮助!!!

于 2019-09-10T05:21:57.550 回答
1

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

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

// Within a component
const { t } = useTranslation()
not_a_component(t)
于 2020-06-05T10:05:01.943 回答