react-i18next:未翻译的字符串

react-i18next: strings not being translated

我在使用 react-i18next 库时遇到了一个令人沮丧的问题。我只是无法让库翻译我的应用程序中的字符串。

代码如下:

App.tsx:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import resources from './resources';

// code omitted...

i18n
  .use(initReactI18next)
  .init({
    resources,
    lng: 'en',
    interpolation: {
      escapeValue: false,
    },
  });

// rest of the code here...

resources/index.tsx:

export default {
  en: {
    'Math Visualized': 'Math Visualized asd',
  },
  fi: {
    'Math Visualized': 'Matematiikan visualisointia',
  },
};

components/header/Header.tsx:

import { withTranslation } from 'react-i18next';

// code omitted...

class HeaderComponent extends React.Component<Props, State> {
  render() {
    const { headerText, subheaderText, t } = this.props;

    // react-bootstrap used here
    return (
      <Navbar bg="dark" variant="dark">
        <Navbar.Brand>{t(headerText)}</Navbar.Brand>
        {subheaderText && <Navbar.Text>{t(subheaderText)}</Navbar.Text>}
      </Navbar>
    );
  }
}

export const Header = withTranslation()(HeaderComponent);

header 和 subheader 文本字符串根本拒绝翻译。

我只是忘记将 translation 命名空间添加到资源文件中。我是这样修改的:

export default {
  en: {
    translation: { // THIS NAMESPACE HERE WAS MISSING
      'Math Visualized': 'Math Visualized asd',
    },
  },
  fi: {
    translation: {
      'Math Visualized': 'Matematiikan visualisointia',
    },
  },
};

一切正常。