【问题标题】:react-i18Next: Using an enum for translation key valuesreact-i18Next:使用枚举作为翻译键值
【发布时间】:2021-09-18 20:18:56
【问题描述】:

我们在我们的 React 项目中使用 i18Next,我想知道是否有办法使用枚举作为翻译文件的键以避免在这样使用时出现拼写错误:

export enum AppLocaleKey {
  test = 'test'
}

...

import translationEN from './locales/en/translation';
const resources = {
  en: { translation: translationEN },
  ...
};

i18n
  .use(initReactI18next)
  .init({
    resources,
    ...
  })

...

const translation = {
  [AppLocaleKey.test]: 'Test...',
};

export default translation;

...

import { AppLocaleKey } from './locales/localeKeys';
import { useTranslation } from 'react-i18next';

const App = (props: Props) => {
  const { t, i18n } = useTranslation();
  return (
    <>
      <p>{t(AppLocaleKey.test)}</p>
    <>
  )
}

但这没有用。你知道有什么类似的方法吗?

【问题讨论】:

    标签: reactjs enums internationalization i18next react-i18next


    【解决方案1】:

    如果您使用 TS,您可以使用 ts4.1 将 json 的所有键声明为有效输入。

    查看official example

    还有working example

    【讨论】:

      猜你喜欢
      • 2021-04-11
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 2022-06-12
      • 2022-11-30
      相关资源
      最近更新 更多