英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论