react-i18next – 如何使用 t() 访问包含动态值的 js 文件中的嵌套键

huangapple go评论55阅读模式
英文:

react-i18next - How to access nested keys in a js file with dynamic values using the t()

问题

我期望 t(action[EDIT].title) 返回字符串 'Edit'
英文:

Please how do I call action[EDIT].title using t() function in order to return the string "Edit". The EN.js file that contains my translation is like this

// EN.js

const EDIT = "EDIT";
const DELETE = "DELETE";

action: {
    [EDIT]: {
      title: 'Edit',
    },
    [DELETE]: {
      title: 'Delete',
    },
}

and my config is

// i18n.js

const resources = {
  en: {
    translation: EN
  },
  de: {
    translation: DE
  },
};
i18next
  .use(initReactI18next)
  .init({
    resources,
    lng: 'en',
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false,
    },
    debug: true,
  });

export default i18next;

I expect for t(action[EDIT].title) to return the string 'Edit'

答案1

得分: 0

为了访问具有动态值的翻译文件中的嵌套键,您应该修改翻译对象以包括命名空间或键路径。然后,您可以使用 t() 函数与路径一起。

首先,更新您的 EN.js 文件以包括动作对象的命名空间或键路径:

// EN.js
const EDIT = "EDIT";
const DELETE = "DELETE";

const EN = {
  action: {
    [EDIT]: {
      title: 'Edit',
    },
    [DELETE]: {
      title: 'Delete',
    },
  },
};

export default EN;

现在,您可以使用 t() 函数按以下方式访问嵌套键:

const editTitle = t('action.EDIT.title');
英文:

To access the nested keys in your translation file with dynamic values, you should modify your translation object to include a namespace or key path. Then, you can use the t() function with the path.

First, update your EN.js file to include a namespace or key path for the action objects:

// EN.js
const EDIT = "EDIT";
const DELETE = "DELETE";

const EN = {
  action: {
    [EDIT]: {
      title: 'Edit',
    },
    [DELETE]: {
      title: 'Delete',
    },
  },
};

export default EN;

Now, you can access the nested key using the t() function like this:

 const editTitle = t('action.EDIT.title');

答案2

得分: 0

我遇到了这种阻碍,使用点表示法而不是括号表示法对我有用。我不需要修改翻译文件,只需简单地执行 t('action.EDIT.title') 就可以。

英文:

I encountered this kind of blocker and using a dot notation instead of bracket notation worked for me. I didn't need to modify the translation file tho but simply doing t('action.EDIT.title') worked.

huangapple
  • 本文由 发表于 2023年4月20日 01:52:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定