You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在React中如何使用i18n翻译值作为对象的键

解决方法

你当前的写法不符合JS对象的语法规则,静态声明对象时如果要使用表达式作为键,必须使用ES6的计算属性名语法,将表达式放在方括号[]内包裹。

方案1:直接使用计算属性(仅需初始化一次时使用)

const initialValues = {
  [i18n.t("name.drawing")]: {
    items: [],
    startDate: null,
    endDate: null,
  },
  [i18n.t("name.dancing")]: {
    items: [],
    startDate: null,
    endDate: null,
  },
};

该方案仅适用于不需要响应语言切换的场景,如果切换页面语言后对象键需要同步更新,不要用这种写法。

方案2:适配React组件+响应语言切换

如果是在React组件内使用,结合useMemo监听语言变化,自动重新计算对象:

import { useTranslation } from 'react-i18next';
import { useMemo } from 'react';

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

  const initialValues = useMemo(() => ({
    [t("name.drawing")]: {
      items: [],
      startDate: null,
      endDate: null,
    },
    [t("name.dancing")]: {
      items: [],
      startDate: null,
      endDate: null,
    },
  }), [t, i18n.language]);

  // 后续业务逻辑
}

更推荐的最佳实践

不建议直接用翻译值作为对象的键,翻译文本存在空格、特殊字符、后续文案调整的可能性,会导致逻辑层的键值匹配失效。更稳妥的做法是用固定标识作为键,UI渲染时再翻译对应的标识:

// 逻辑层用固定键,不受翻译影响
const initialValues = {
  drawing: {
    items: [],
    startDate: null,
    endDate: null,
  },
  dancing: {
    items: [],
    startDate: null,
    endDate: null,
  },
};

// 渲染到UI时再做翻译
Object.keys(initialValues).forEach(typeKey => {
  const showLabel = t(`name.${typeKey}`);
  // 用showLabel渲染展示文本即可
})

内容的提问来源于stack exchange,提问作者Anetta Dominic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 13:57:02