withTranslation HOC仅在第一个命名空间中查找翻译

问题描述 投票:0回答:1

我正在将我的项目从i18next^11.0.0升级到i18next^15.0.0react-i18next^7.0.0react-i18next^10.0.0。我之前使用的是translate HOC,但现在它已经被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 key的翻译在about名称空间中定义,而name key的翻译在application名称空间中。但是,新版本的库不会在上面的示例中翻译name键:

如果我在about电话中更改applicationwithTranslation的订单

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

一切都变得相反(supported-browsers没有翻译):

在旧版本的react-i18next nsMode option was available解决了这个问题,但它不再起作用了:

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
  }
});

我在documentation找不到与此有关的任何内容。这是一个例子:

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

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

Migration guide from 9 to 10没有强调这种行为的任何变化。

i18next react-i18next
1个回答
0
投票

react-i18next版本以来,nsMode没有10.0.0。但this pull request补充说(发表于10.7.0)。

人们可以通过命名空间(withTranslation)为键添加前缀来翻译文本(即使没有将名称空间传递给useTranslationns:key):

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('application:name')} {VERSION}
      </p>

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

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

export default withTranslation()(AboutControl);

当你使用withTranslation确保它们在渲染之前可用时,需要将命名空间传递给load translation resources asynchronously

© www.soinside.com 2019 - 2024. All rights reserved.