reactjs - Ant Design 如何处理 Form.List 从底层数据结构访问值?

我尝试掌握 Form.List from Ant Design .我已经知道它包含 FieldData[],其中每个元素都包含 name, key, fieldKey 但我不知道如何使用它来访问它的值。我尝试基于 code sample I found in another question 解决以下两个用例:

  • 页脚将所有年龄相加为所有用户的总年龄
  • 为年龄和姓名添加排序器,也就是数字和字符串列

从上面浓缩codesandbox示例 我有以下表格和表格代码,留下了我无法解决的两个 TODO。你能帮帮我吗?

如果一般情况下,您对 Form.List 有所了解,这也会有很大帮助吗?例如解释为什么我需要它用于动态表单以及它在内部和组件中做什么?

非常感谢任何帮助。

import { Button, Form, Row, notification, Table, InputNumber } from "antd";
import React, { useState } from "react";
import { useForm } from "antd/lib/form/util";

const TestForm: React.FC = () => {
 const [data, setData] = useState({ users: [] });
 const [form] = useForm();
 const [editingIndex, setEditingIndex] = useState<number | undefined>(
   undefined
   );

 const onFinish = (values: any) => {
   notification.success({
       message: "Submit",
       description: `Received values of form: ${JSON.stringify(values)}`
   });
   setData(values);
   };

 return (
  <Form
  form={form}
  name="dynamic_form_item"
  onFinish={onFinish}
  initialValues={data}
  >
   <Form.List name="users">
    {(users, { add, remove }) => (
     <Table
      dataSource={users}
      pagination={false}
      footer={fields => {
       // TODO calculate age sum from fields
       return (
           <Button>Add User</Button>
       );
      }}
      >
       <Table.Column
           dataIndex={"age"}
           title={"Age"}
           width={125}
           sorter={() => {
             // TODO build something to sort here sorter: (a, b) => a.weight - b.weight,
             return 0;
           }}
           render={(value, row, index) => {
            return (
             <EditableFormItem
                 name={[index, "age"]}
                 editing={index === editingIndex}
                 className={"ant-form-item-no-bottom-margin"}
                 >
                 <InputNumber placeholder="age" min={0} max={150} />
             </EditableFormItem>
            );
           }}
       />
      </Table>
     )}
    </Form.List>
   </Form>
  )};

export default TestForm;

最佳答案

诀窍是使用整个 NamePath访问字段的值。

  • 你的 <Form.List>具有名称属性 "users"
  • 当您映射字段:Field[](在您的例子中称为users)时,ant 将每个字段的索引映射到name 参数.

将此信息与字段的实际输入名称结合起来,您将得到字段 NamePath通过 form.getFieldValue() 访问表单条目的值:

form.getFieldValue(["users", name, "age"])

https://stackoverflow.com/questions/61381633/

相关文章:

ios - 如何在 SwiftUI 中更新 TextField 的值?

angular - JSDom karma Angular 设置

google-app-engine - 将 AppEngine 中的传入请求路由到不同版本

r - 如何使用 knitr::kable() 将两个不同大小的表并排顶部对齐

python - 为什么输入永无止境

python - 为什么在 Python 中从不同路径调用类时 __class__ 不同?

vba - 在 64 位 VBA 中使用 TaskDialogIndirect

swiftui - 如何在 SwiftUI 中使 UIViewRepresentable 可聚焦在

php - 超时作业挂起 15 或 30 分钟,然后运行

javascript - 排序 mongoose-aggregate-paginate-v2 更改顺