useTranslation()挂钩从错误的范围返回t函数

时间:2020-04-21 12:47:50

标签: react-i18next

在我的项目中,我使用react-i18next进行翻译。在我的组件中,我通过t HOC获得了withTranslation()函数。在其中一个组件中,我使用了从公司内部库中导入的子组件Table。该库还单独使用react-i18next实现了i18n。但是,Table组件中的字符串未翻译。

import React from 'react';
import { withTranslation } from 'react-i18next';
import { Table } from 'internal-library';

class MainComponent extends React.Component {
  render () {
    const { t, i18n } = this.props;
    return (
      <>
        <h1>
          {t('Table of objects')}
        </h1>
        <Table
          locale={i18n.language}
        />
      </>
    );
  }
}

export default withTranslation('common')(MainComponent)

在调试时,我发现了错误的原因。在Table的代码中,t函数是使用useTranslation()钩子获得的。出于某种原因,该挂钩从我项目的范围而不是库的范围返回t。我的数据库中没有Table的字符串,因此翻译失败。

解决此错误的方法可能是explicitly passingi18n钩子的useTranslation()实例。可悲的是,修改库的代码不是一种选择,因为它是重要项目的依赖项。我无法将缺少的字符串添加到数据库中,因为该库对密钥使用了不同的模式,这会破坏数据库。

还有其他解决方案吗?

0 个答案:

没有答案