在return方法中使用导入的函数(无效的hook调用,react js)



Wassup Guys,

我有一个可重用组件,它通过字符串或绑定的var.的注释名将键转换为选定的语言

通常我会使用一个标签,但由于不同的原因,我会用{t("…"(}切换/替换当前的翻译。

这是组件的代码:

import React from 'react';
import { useTranslation as defaultTranslation } from 'react-i18next';
import i18next from 'i18next';
export const useTranslation = (ns = 'common', options) => {
return defaultTranslation(ns, {
useSuspense: false,
...options,
});
};
export const withTranslation = (Component, ns, options) => {
const TranslatedHOC = (props) => {
const translationProps = useTranslation(ns, options);
return <Component {...translationProps} {...props} />;
};
return TranslatedHOC;
};
export const getCurrentLanguage = () =>
i18next.language || localStorage.getItem('language') || 'de-DE';

首先,我为使用的导入函数定义常量:

const{t}=useTranslation((;

正常情况:在文件中导入我的组件,我想在其中使用它并添加上面的代码。

我的组件的代码,我想在其中替换标记。


// Import React Table
import ReactTable from 'react-table';
import 'react-table/react-table.css';
import LocalizedText from '@components/i18n/LocalizedText';
class T extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
pages: null,
loading: true,
};
this.fetchData = this.fetchData.bind(this);
}
fetchData(state, instance) {
this.props.onFetchData(state, instance).then(() => {
this.setState({
loading: false,
});
});
}
render() {
return (
<ReactTable
{...this.props}
previousText={
<LocalizedText textKey="caseoverview.orderproduct.back" />
}
nextText={
<LocalizedText textKey="caseoverview.orderproduct.continue" />
}
loadingText={<LocalizedText textKey="loading" />}
noDataText={<LocalizedText textKey="placeholders.nodata" />}
pageText={
<LocalizedText textKey="reservationcalculator.search.result.page" />
}
ofText={<LocalizedText textKey="from" />}
rowsText={<LocalizedText textKey="rows" />}
className="case-search-table"
/>
);
}
}
export default T;
...
previousText={
<LocalizedText textKey="caseoverview.orderproduct.back" />
}
...

应更改为:

...
previousText={
t('caseoverview.orderproduct.back')
}
...

问题是,我不能在使用上面引用的代码时不遇到任何关于无效钩子调用的问题。如果我以某种方式将其移出,我会收到错误,告诉我我的not'要么没有定义,要么是一个意外的令牌。有人能帮我吗?在线搜索解决方案,没有任何结果。

钩子只能在功能组件中使用。您可以将这个类组件更改为函数组件,也可以使用react-i18nextwithTranslationHOC来包装您的类组件。看见https://react.i18next.com/latest/withtranslation-hoc#when-使用

@kevinasworth的回答帮助了我。使用withTranslation并将t传递为道具

const{t}=this.ops;

内部的渲染方法对我有效。

最新更新