Evi*_*unk 8 javascript reactjs react-i18next
我正在将 React 与 react-i18next 一起使用
我的 index.tsx 文件包含一些组件,我可以在那里使用翻译功能
index.js
import React, { Suspense } from 'react'
import ReactDOM from 'react-dom';
import * as utils from './Utils';
import './i18n';
import { useTranslation, withTranslation, Trans } from 'react-i18next';
...
const { t, i18n } = useTranslation();
//I can use the translate function here
t("title");
//call a util function
utils.helperFunction(...);
...
Run Code Online (Sandbox Code Playgroud)
这里一切正常。我现在在一个附加文件中创建了一些辅助函数
Utils.tsx
...
import { useTranslation, withTranslation, Trans } from 'react-i18next';
...
export function helperFunction(props: any){
//do stuff
//now I need some translation here - but useTranslation is not working?
const { t, i18n } = useTranslation();
t("needTranslation");
}
Run Code Online (Sandbox Code Playgroud)
如何在辅助函数中使用相同的翻译逻辑?(不必总是将t函数传递给辅助方法)
或者钩子的使用在这里是错误的方法?
出现以下错误
React Hook "useTranslation" is called in function "helperFunction" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
Run Code Online (Sandbox Code Playgroud)
Evi*_*unk 11
我不再使用useTranslation钩子解决了我的问题
相反,我将i18n初始化移动到一个文件 (i18n.tsx -exports i18n) 并在我的 Utils 类中导入和使用它
我的Utils.tsx文件看起来不像这个 Utils.tsx
...
import i18n from '../i18n';
...
export function helperFunction(props: any){
//do stuff
//use imported i18n and call the t() method
i18n.t("needTranslation");
}
Run Code Online (Sandbox Code Playgroud)
i18n.tsx
...
import i18n from '../i18n';
...
export function helperFunction(props: any){
//do stuff
//use imported i18n and call the t() method
i18n.t("needTranslation");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6977 次 |
| 最近记录: |