0

我正在使用 HttpBackend 动态加载翻译但是在我的组件中,我使用 Trans 组件,并且它在尖叫缺少翻译键,我还看到 init 在尝试访问 Trans 组件后完成。我的应用程序有一个暂停,为什么会发生这种情况?

我进入控制台: i18next::translator: missingKey en translation myKey 这是其中包含 a 的文本
.... init 发生在之后。

我怎样才能解决这个问题?

// file: i18n.js
i18n
  // load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
  // learn more: https://github.com/i18next/i18next-http-backend
  .use(Backend)
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    fallbackLng: 'en',
    debug: true,
    supportedLngs: ['en', 'bg', 'rs'],
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    backend: {
      loadPath: '/static/{{lng}}.translations.json',
    },
    react: {
      wait: true,
      useSuspense: true,
    },
    transSupportBasicHtmlNodes: true,
  });

export default i18n;

// app.js
function App() {
  return (
    <BrowserRouter>
      <Apollo>
        <Suspense fallback={<Loading />}>
          <ThemeProvider theme={theme}>
            <Header />
            <Routes />
            <Footer />
          </ThemeProvider>
        </Suspense>
      </Apollo>
    </BrowserRouter>
  );
}

有问题的组件:

//home
const I18N_TEXT_KEY_CONSTANT = 'text_key';
const Home = () => (
  <Trans i18nKey={I18N_TEXT_KEY_CONSTANT}>
    This is text that has a <br /> in it and also some random spaces.
  </Trans>
);    
4

2 回答 2

1

您应该将t函数传递给Trans组件。

//home
import { useTranslation } from 'react-i18next';
const I18N_TEXT_KEY_CONSTANT = 'text_key';

const Home = () => {
  const { t } = useTranslation();
  return (
    <Trans i18nKey={I18N_TEXT_KEY_CONSTANT} t={t}>
      This is text that has a <br /> in it and also some random spaces.
    </Trans>
  );
};   
于 2021-03-10T08:36:17.653 回答
0

遗憾的是没有记录的解决方案是:

const {t}  = useTranstions()
<Trans i18nKey="someKey" t={t}>

将 t 传递给 Trans 非常有效。

于 2021-03-10T08:34:53.610 回答