Antd Ant Design Form Form.List 使用Demo 使用方法

姜运珧
2023-12-01
import React, {useState, useEffect} from 'react';
import {Modal, message, Form, Button, Space, Select, Input} from 'antd';
import styles from './index.less';
import {MinusCircleOutlined, PlusOutlined} from '@ant-design/icons';

export default function BatchAddColumns(props) {
  const {show, setShow, objId, tablePro} = props;
  const [form] = Form.useForm();

  function setShowClose() {
    setShow(false);
  }

  useEffect(() => {
    if (show) {
      form.setFieldsValue({
        cols: [{}, {},], // 初始化数据
      })
    }

  }, [show]);
  const config = [
   {
      Com: Input,
      name: 'title',
      label: '字段中文简称',
      rules: [{required: true}],
      initialValue: '',
      props: {
       
      },
    },
   {
    
      Com: Input,
      name: 'name',
      label: '字段key',
      rules: [{required: true}],
      initialValue: '',
      props: {
     
      },
    },
];

  const saveValues = () => {
    return form.validateFields().then((values: any): void => {
      if (!values.cols || !values.cols.length) {
        throw new Error('没有获取到要新增的字段');
      }
      console.log(values);
    });
  };

  return (
    <Modal visible={show}
           width={1800}
           title={'批量新增字段'}
           onCancel={setShowClose}
           onOk={saveValues}
           bodyStyle={{height: '50vh', overflowY: 'auto'}}
    >
      <div className={styles.OneFileds}>
        <Form autoComplete="off"
              form={form}
        >
          <Form.List name="cols">
            {(fields, {add, remove}) => (
              <>
                {fields.map(field => (
                  <Space key={field.key}
                         style={{display: 'flex', marginBottom: 8}}
                         align="baseline">
                    <a onClick={() => {
                      let newData = form.getFieldsValue().cols;
                      if(newData[field.key].title){
                        form.setFieldsValue({
                            cols: [],
                          });
                          newData[field.key] = {
                            ...newData[field.key],
                            name: '翻译',
                          };
                          form.setFieldsValue({
                            cols: newData,
                          });
                     
                      }
                    }}>
                      翻译
                    </a>

                    {
                      config.map((Y) => {
                        return (
                          <Form.Item
                            key={Y.name}
                            label={Y.label}
                            {...field}
                            name={[field.name, Y.name]}
                            fieldKey={[field.fieldKey, Y.name]}
                            rules={Y.rules || []}
                            initialValue={Y.initialValue}
                          >
                            <Y.Com {...Y.props}/>
                          </Form.Item>
                        )
                      })
                    }
                    <MinusCircleOutlined onClick={() => {
                      return remove(field.name);
                    }}/>
                  </Space>
                ))}
                <Form.Item>
                  <Button type="dashed"
                          onClick={() => add()}
                          block
                          icon={<PlusOutlined/>}>
                    新增字段
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </div>
    </Modal>
  )
}

注意事项

  1. setFieldsValue 在不改变数据length 只改变某一个字段的值时是有可能失败的.
    因为 react 的虚拟dom比对数据变化是浅比对.
    我的解决方案是 先 设置为空数组, 再设置成更新后的新数据
let newValue = [ ...dataS ]; //  React diff算法的原因 必须深拷贝 Dom才能更新
setData(newValue);

 类似资料: