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

如何在Mantine Form中访问值为数组的Map类型对象字段?

Mantine Form 访问Map类型字段的正确方式

Mantine Form的点分隔路径语法无法正确解析包含特殊字符(比如连字符-)的Map键,你需要改用方括号语法来指定Map的键,这样就能正确访问到数组中的Field属性。

正确写法

直接使用方括号包裹Map的键(注意键要加引号),再通过索引访问数组元素:

form.getInputProps('assignedFieldsMap["1-1"][0].name')

如果是动态生成的键或索引,可以用模板字符串拼接路径:

const mapKey = '1-1';
const arrayIndex = 0;
form.getInputProps(`assignedFieldsMap["${mapKey}"][${arrayIndex}].name`)

完整示例

以下是一个可运行的表单示例,展示如何初始化Map类型的表单值并绑定输入框:

import { useForm } from '@mantine/form';

interface Field {
  id: string;
  name: string;
}

interface Parent {
  assignedFieldsMap: Map<string, Field[]>;
}

export default function MyForm() {
  const form = useForm<Parent>({
    initialValues: {
      assignedFieldsMap: new Map([
        ['1-1', [{ id: 'field-1', name: '初始字段名' }]],
      ]),
    },
  });

  return (
    <div>
      <input
        type="text"
        {...form.getInputProps('assignedFieldsMap["1-1"][0].name')}
        placeholder="输入字段名"
      />
      <pre>{JSON.stringify(Object.fromEntries(form.values.assignedFieldsMap), null, 2)}</pre>
    </div>
  );
}

原理说明

Mantine Form的路径解析逻辑中,点分隔符会被当作对象属性的分隔符,但Map的键不属于对象属性,且当键包含特殊字符时,点语法会解析失败。方括号语法可以明确指定要访问的Map键,无论键包含什么字符都能正确识别,再结合数组索引就能精准定位到Field的name属性。

内容的提问来源于stack exchange,提问作者Vas K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:04:57