antd4,使用表格表单,怎么绑定字段名

发布于 2022-09-13 01:03:03 字数 2414 浏览 19 评论 0

import { FormInstance, Input, Table, Form, Button } from "@jd/antd";
import React from "react";
import "./index.less";

type Item = {
  id: string
  name: string
  age: string
}
export interface TestListProps {

}

export interface TestListState {
  dataSource: Item[]
}

class TestList extends React.Component<TestListProps, TestListState> {
  formRef = React.createRef<FormInstance>();
  constructor(props: TestListProps) {
    super(props);
    this.state = { dataSource: [] };
  }
  handleClick = () => {
    this.formRef.current?.validateFields().then((values) => {
      const _params = values;
      console.log(_params);
    }).catch(err => {
      console.log(err);
    });
  }
  handleAdd = () => {
    const { dataSource } = this.state;
    this.setState({
      dataSource: [...dataSource, {id: "", name: "", age: ""}]
    });
  }
  render() {
    const { dataSource } = this.state;
    const _columns = [
      {
        title: "id",
        render: (text: any, record: any, index: number) => {
          return <Form.Item name={`${(dataSource[index] as any).id}`}>
            <Input></Input>
          </Form.Item>;
        }
      },
      {
        title: "name",
        render: (text: any, record: any, index: number) => {
          return <Form.Item name={`${(dataSource[index] as any).name}`}>
            <Input></Input>
          </Form.Item>;
        }
      },
      {
        title: "age",
        render: (text: any, record: any, index: number) => {
          return <Form.Item name={`${(dataSource[index] as any).age}`}>
            <Input></Input>
          </Form.Item>;
        }
      }
    ];
    return (
      <div>
        <Form ref={this.formRef} >
          <Table
            columns={_columns}
            dataSource={dataSource}
            rowKey={"id"}
          ></Table>
        </Form>
        <Button type="primary" onClick={this.handleAdd}>添加</Button>
        <Button type="primary" onClick={this.handleClick}>提交</Button>
      </div>);
  }
}

export default TestList;


添加一行后,输入1,三个输入框都是1了,点击提交获取到表单的值为:
{"": "1"}

我想达到的效果是添加两行,输入框的依次输入1,2,3,4,5,6,点击提交按钮后得到表单的值为:

[
{id:1,name:2,age: 3},
{id:4,name:5,age: 6}
]

请问怎么修改下?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文