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

点击antd Table行编辑按钮将行数据填充到其他组件antd Input的问题

问题根源

  1. Ant Design 的 Form 组件 initialValues 属性仅在组件首次挂载时生效,后续 selectedRecord 状态更新时,不会自动触发表单值的重渲染。
  2. 你在 Input 组件上手动绑定了 value 属性,和 Form 的受控模式冲突,Form.Item 会自动接管绑定了 name 属性的表单项的值,无需手动指定 value。

解决方案

步骤1:修改 RecordsForm 组件

通过 useEffect 监听 selectedRecord 变化,调用 Form 实例的 setFieldsValue 方法手动更新表单值,同时删除 Input 上的 value 属性:

import React, { useEffect } from "react";
import { Input, Form } from "antd";
import { SaveOutlined } from "@ant-design/icons";

const RecordsForm = ({ selectedRecord, recordComponentForm }) => {
  console.log(selectedRecord);
  // 监听选中记录变化,更新表单值
  useEffect(() => {
    if (selectedRecord) {
      recordComponentForm.setFieldsValue({
        Title: selectedRecord.Title
        // 后续新增其他表单项字段也可以在这里统一赋值
      })
    } else {
      // 选中记录为空时清空表单
      recordComponentForm.resetFields()
    }
  }, [selectedRecord, recordComponentForm])

  return (
    <Form
      name="seasonForm"
      initialValues={{ Title: "" }}
      autoComplete="off"
      layout={"inline"}
      form={recordComponentForm}
    >
      <Form.Item
        label="Title"
        name="Title"
        rules={[{ required: true, message: "Add a Title" }]}
      >
        <Input
          name="Title"
          placeholder="Record Title"
          // 删掉手动绑定的value属性
        />
      </Form.Item>
    </Form>
  );
};

export default RecordsForm;

步骤2:优化 ModalButton 组件的关闭逻辑

关闭弹窗时清空选中记录,避免下次打开弹窗还残留上次的编辑数据:

// 仅展示修改的部分代码
const handleOk = () => {
  setIsModalVisible(false);
  setSelectedRecord(undefined);
  recordComponentForm.resetFields();
};

const handleCancel = () => {
  setIsModalVisible(false);
  setSelectedRecord(undefined);
  recordComponentForm.resetFields();
};

修改完成后点击编辑按钮即可正常回显表单值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:36:03