首页 > 解决方案 > withTranslation HOC 仅在第一个命名空间中查找翻译

问题描述

我正在将我的项目从i18next^11.0.0toi18next^15.0.0react-i18next^7.0.0to升级到react-i18next^10.0.0. 我以前使用translateHOC,但现在似乎已被withTranslation取代。因此,在这些更改之后,我的简单 React 组件如下所示:

import React from 'react';
import { withTranslation } from 'react-i18next';

const AboutControl = props => {
  const { t } = props;

  return (
    <div className="about-control">
      <p className="about-control-application-name">
        {t('name')} {VERSION}
      </p>

      <p>
        {t('supported-browsers')}:
      </p>

      <ul>
        <li>Google Chrome >= 55</li>
        <li>Mozilla Firefox >= 53</li>
      </ul>
    </div>
  );
};

export default withTranslation(['about', 'application'])(AboutControl);

键的翻译supported-browsers在命名空间中定义,aboutname键的翻译在application命名空间中。但是,新版本的库不会name在上面的示例中翻译密钥:

如果我更改about通话application顺序withTranslation

export default withTranslation(['application', 'about'])(AboutControl);

反之亦然(supported-browsers未翻译):

在旧版本的react-i18next nsMode 选项中可以使用该选项解决了该问题,但它不再起作用:

await i18next.init({
  whitelist: this.languages,
  lng: this.language || this.languages[0],
  fallbackLng: this.languages[0],
  lowerCaseLng: true,
  debug: false,
  resources: {},
  interpolation: {
    escapeValue: false // not needed for React
  },
  react: {
    wait: true,
    nsMode: true
  }
});

我在文档中没有找到与此相关的任何内容。这是那里的一个例子:

// load multiple namespaces
// the t function will be set to first namespace as default
withTranslation(['ns1', 'ns2', 'ns3'])(MyComponent);

看起来不需要任何额外的选项,否则我想知道如果不翻译组件的文本应该传递哪些命名空间。它是一个错误吗?或者是否存在任何解决方法?

从 9 到 10 的迁移指南并未突出显示对此行为的任何更改。

标签: i18nextreact-i18next

解决方案


我遇到了同样的问题(省略了 withTranslation 函数中指定的 ns),在寻找解决方案但没有找到任何东西之后,我尝试了一些不同的方法,这是正确的解决方案。

您可以配置要使用的命名空间,而不是按命名空间的前缀键:

const {t} = useTranslation ('yourNSname');

您可以继续使用前缀键来访问来自其他命名空间的值。

我希望它可以帮助你或有同样问题的人。


推荐阅读