【问题标题】:Using react-i18next as a translation provider for React Admin使用 react-i18next 作为 React Admin 的翻译提供者
【发布时间】:2021-04-11 10:41:22
【问题描述】:

我正在尝试使用 react-i18next 作为 react-admin 的翻译提供者。 React-admin 提供了有关如何设置 custom translation provider 的文档。

这很容易理解,我为 i18next 创建了一个:

export const i18nProvider = {
    translate: (key, { _, smart_count, ...rest } = {}) => {
        return i18n.t(key, {
            defaultValue: _,
            count: smart_count,
            ...rest,
        });
    },
    changeLocale: (locale) => i18n.changeLanguage(locale),
    getLocale: () => i18n.language,
};

我遇到的问题是 react-i18next 使用 suspense 来加载翻译,当像这样直接调用 i18n.t 函数而不是通过 hook 时,这种行为似乎不起作用:

import React, { Suspense } from 'react';
import { useTranslation } from 'react-i18next';

function MyComponent() {
  const { t, i18n } = useTranslation();

  return <h1>{t('Welcome to React')}</h1>
}

// i18n translations might still be loaded by the http backend
// use react's Suspense
export default function App() {
  return (
    <Suspense fallback="loading">
      <MyComponent />
    </Suspense>
  );
}

最终发生的情况是,在加载翻译之前调用了 i18n.t 函数,并且最终不显示翻译。

有没有更好的方法将 react-i18next 与 react admin 集成?

【问题讨论】:

    标签: react-admin


    【解决方案1】:

    实例化 i18n 并在安装应用时简单地导入它

    import i18n from 'i18next';
    import { initReactI18next } from 'react-i18next';
    
    import frTranslations from '~/locales/fr.json';
    
    i18n
      // pass the i18n instance to react-i18next.
      .use(initReactI18next)
      // init i18next
      // for all options read: https://www.i18next.com/overview/configuration-options
      .init({
        fallbackLng: 'fr',
        resources: {
          fr: { translation: frTranslations },
        },
      });
    
    export default i18n;
    
    import App from './App';
    
    import './i18n';
    
    ReactDOM.render(<App />, document.getElementById('root'));
    

    然后你就可以像你一样使用它了

    import { useTranslation } from 'react-i18next';
    
    function SearchFilter(props) {
      const { t } = useTranslation();
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 1970-01-01
      • 2021-09-18
      • 2020-12-21
      • 2022-06-12
      • 2021-07-20
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多