首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用react-i18next作为React Admin的翻译提供程序

使用react-i18next作为React Admin的翻译提供程序
EN

Stack Overflow用户
提问于 2021-01-06 00:40:01
回答 1查看 241关注 0票数 0

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

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

代码语言:javascript
复制
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调用时,这种行为似乎不起作用

代码语言:javascript
复制
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?

EN

回答 1

Stack Overflow用户

发布于 2021-01-06 01:27:22

实例化i18n并在挂载应用程序时简单地导入它

代码语言:javascript
复制
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;
代码语言:javascript
复制
import App from './App';

import './i18n';

ReactDOM.render(<App />, document.getElementById('root'));

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

代码语言:javascript
复制
import { useTranslation } from 'react-i18next';

function SearchFilter(props) {
  const { t } = useTranslation();
  ...
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65582995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档