【问题标题】:How to use react-i18next in a utility function outside the component tree?如何在组件树外的实用函数中使用 react-i18next?
【发布时间】:2019-11-09 19:32:51
【问题描述】:

我关注了react-i18next docs 并将我的 React 应用程序国际化。

我使用useTranslation 钩子,它给了我“t”对象。目前一切顺利,但我有一些非 Hook 实用程序函数,它们位于组件树之外。

如何访问那里的翻译对象?

【问题讨论】:

    标签: reactjs internationalization i18next react-i18next


    【解决方案1】:

    这似乎可行,导入i18next 而不是react-i18next

    // import { useTranslation } from "react-i18next";
    import i18next from "i18next";
    function hello() {
        return i18next.t("hello");
    }
    

    【讨论】:

      【解决方案2】:

      这个对我有用,

      //导入i18next

      import i18next from 'i18next';
      

      //那么你需要像这样尝试的地方

      i18next.t('common:messages.errorMessage')
      

      【讨论】:

        【解决方案3】:

        不确定它是否会起作用,但你可以试试这个:

        import i18n from "react-i18next";
        
        // Then where ever you need try to this
        
        i18n.t("target")
        

        【讨论】:

        • @PaulRazvanBerg ,如何将 i18n.t 函数设置为 Class 的静态属性或其他东西,然后从外部组件静态访问该 i18n.t 函数
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-15
        • 2019-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 2021-12-24
        相关资源
        最近更新 更多