【问题标题】:How to use react-i18next inside BASIC function (not component)?如何在 BASIC 函数(不是组件)中使用 react-i18next?
【发布时间】:2019-09-10 04:29:49
【问题描述】:

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

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

const translate = not_a_component();

错误挂钩!

谢谢!

【问题讨论】:

    标签: react-i18next


    【解决方案1】:

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

    希望对你有帮助!!!

    【讨论】:

      【解决方案2】:

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

      const not_a_component = (t) => {
        return t('translation')
      };
      
      // Within a component
      const { t } = useTranslation()
      not_a_component(t)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-02
        • 2019-07-13
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 2020-02-15
        相关资源
        最近更新 更多