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

Antd Form中useWatch无法访问Form.List内嵌套表单项的问题

解决Ant Design Form.List内表单项无法被Form.useWatch监听的问题

问题核心在于Form.List的表单值是数组结构,你直接用Form.useWatch("name")找不到对应字段——Form.List会把内部表单项的值包裹在数组中,字段路径不是单纯的name,而是[列表名][索引].name。

正确实现步骤

  1. 给Form.List指定明确的name属性(比如name="users"),让表单值以数组形式存储。
  2. 在Form.List的渲染函数中,通过field.name(列表项的索引标识)拼接表单项的name,比如[field.name, 'name'],自动关联数组的对应索引位置。
  3. 使用Form.useWatch监听整个列表的路径(比如"users"),再从中提取目标表单项的值。

修改后的代码示例

import React from "react";
import { Form, Input, InputNumber, Typography } from "antd";

const Demo = () => {
  const [form] = Form.useForm();
  // 监听整个users列表的变化
  const users = Form.useWatch("users", form);
  // 提取第一个列表项的name值
  const nameValue = users?.[0]?.name;

  return (
    <>
      <Form form={form} layout="vertical" autoComplete="off">
        {/* 给Form.List指定name,定义表单值的根路径 */}
        <Form.List name="users">
          {(fields, { add, remove }) => (
            <>
              {fields.map((field) => (
                <div key={field.key}>
                  {/* 用field.name拼接表单项的name,对应数组索引+字段名的路径 */}
                  <Form.Item
                    name={[field.name, "name"]}
                    label="Name (Watch to trigger rerender)"
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={[field.name, "age"]}
                    label="Age (Not Watch)"
                  >
                    <InputNumber />
                  </Form.Item>
                  <button onClick={() => remove(field.name)}>删除</button>
                </div>
              ))}
              <button onClick={() => add()}>添加用户</button>
            </>
          )}
        </Form.List>
      </Form>

      <Typography>
        <pre>Name Value: {nameValue}</pre>
      </Typography>
    </>
  );
};

export default Demo;

关键说明

  • Form.List的name属性定义了表单值的根路径,比如users对应form.getFieldValue('users'),返回的是一个数组。
  • field.name是当前列表项的索引(数字),[field.name, 'name']会被解析为类似users[0].name的路径,精准对应列表项的字段。
  • 若要监听所有列表项的name变化,直接监听users即可,任何列表项的字段修改都会触发users更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:37:44