如何在组件树之外的实用函数中使用react-i18next?

Pau*_*erg 7 internationalization i18next reactjs react-i18next

我遵循了react-i18next文档并将我的React应用程序国际化。

我使用useTranslation钩子,它给了我“t”对象。现在一切都很好很顺利,但是我有一些位于组件树之外的非 Hook 实用函数。

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

wes*_*sel 6

这似乎有效,导入i18next而不是react-i18next

// import { useTranslation } from "react-i18next";
import i18next from "i18next";
function hello() {
    return i18next.t("hello");
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这对我有用,

//导入i18next

import i18next from 'i18next';
Run Code Online (Sandbox Code Playgroud)

//那么你需要在哪里尝试这样

i18next.t('common:messages.errorMessage')
Run Code Online (Sandbox Code Playgroud)


Sag*_*aev -3

不确定它是否有效,但你可以尝试一下:

import i18n from "react-i18next";

// Then where ever you need try to this

i18n.t("target")
Run Code Online (Sandbox Code Playgroud)