ant.desin Form.Item <Input type="hidden" /> 隐藏元素维护复杂数据类型的值的一种解决方案

3,135 阅读1分钟

遇到了标题的问题,记录一下解决方案

import React from "react";
import { Form } from "antd";

const DrawLane = () => {
  const form = Form.useForm();
  
  useEffect(() => {
    if (form) {
      form.setFieldsValue({
        analyze_config: {
          drawInfo: { lanes: { [0]: { rois: lane.rois } } },
          // drawInfo: { lanes: { [index]: { rois: lane.rois } } },
        },
      });
    }

  }, [form])
  return (
    <Form form={form}>
      <Form.Item name={["analyze_config", "drawInfo", "lanes", 0, "rois"]}>
        <Input type="hidden" />
      </Form.Item>
    </Form>
  )
}
import React, { useRef } from "react";
import { Form } from "antd";

const DrawLane = () => {
  const form = Form.useForm();
  const [cookedLanes, setCookedLanes] = useState([]);
  const lanes = useRef([
    {
      id: "f023-4djj-x3m2",
      name: "车道1",
      rois: [],
      width: 3.75,
    },
    {
      id: "nf32-4djj-f092",
      name: "车道2",
      rois: [375, 280, 490, 280],
      width: 3.75,
    },
  ]);

  useEffect(() => {
    if (lanes.current) {
      lanes.current.forEach((lane) => {
        // 直接在列表渲染的时候设置的话 antd 会警告,因此通过这种形式将 rois 设置到 form.item 中
        form.setFieldsValue({
          analyze_config: {
            // 所有的属性都设置上,不然要踩深坑!!!!2022-04-05 21:48:33
            drawInfo: { lanes: { [index]: { rois: lane.rois } } },
          },
        });
      });

      setCookedLanes(lanes.current);
    }
  }, [lanes.current]);

  const onSubmit = () => {
    form.validateFields().then((values) => {
      // console.log(values);
      // [{ ..., rois: [] },{ ..., rois: [375, 280, 490, 280] }]
      console.log(values.analyze_config.lanes);
    });
  };

  return (
    <Form form={form}>
      {cookedLanes.map((lane, index) => {
        return (
          <div key={lane.id} data-lane-form-item="data-lane-form-item">
            <Form.Item
              name={["analyze_config", "drawInfo", "lanes", index, "rois"]}
              initialValue={lane.rois}
            >
              <Input type="hidden" />
            </Form.Item>
            <Form.Item label="车道宽度">
              <Input value={lane.width} />
            </Form.Item>
          </div>
        );
      })}
      <Button onClick={onSubmit}>提交</Button>
    </Form>
  );
};

export default DrawLane;

参考资料: