【每天学一点-08】Antd 动态增减表单项,默认展示一项

时间:2025-04-03 09:15:09
  • import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
  • import { Form, Input, Button } from 'antd';
  • import { isEmpty } from 'evian';
  • import React from 'react';
  • import './';
  • /* --手机号校验规则-- */
  • const phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
  • function notPhoneNumber(payload: any) {
  • return !phoneReg.test(payload);
  • }
  • function phoneValidator(rule: any, value: any) {
  • if (isEmpty(value)) return Promise.reject('必填项');
  • if (notPhoneNumber(value)) {
  • return Promise.reject('手机号格式错误');
  • }
  • return Promise.resolve();
  • }
  • /* ---------------- */
  • const FormGroup: React.FC = () => {
  • const [form] = Form.useForm();
  • const onFinish = (value: any) => {
  • console.log('values', value);
  • };
  • return (
  • <div className="form-div">
  • <Form className="form" onFinish={onFinish} form={form}>
  • < name="values" label="手机号" required>
  • <
  • name="values"
  • rules={[
  • {
  • validator: async (_, names) => {
  • // 表单项校验(目前至少正确填写一项)
  • if (!names || < 1) {
  • return (new Error('请填写手机号'));
  • }
  • },
  • },
  • ]}
  • >
  • {(fields, { add, remove }, { errors }) => (
  • <>
  • {((field) => (
  • < required={true} key={}>
  • <
  • {...field}
  • validateTrigger={['onChange', 'onBlur']}
  • rules={[
  • {
  • required: true,
  • whitespace: true,
  • validator: phoneValidator, // 手机号校验规则
  • },
  • ]}
  • noStyle
  • >
  • <Input
  • placeholder="请输入手机号"
  • style={{ width: '85%' }}
  • />
  • </>
  • {/* 输入框右侧移除按钮控制(表单项大于一个才显示) */}
  • { > 1 ? (
  • <MinusCircleOutlined
  • className="dynamic-delete-button"
  • onClick={() => remove()}
  • />
  • ) : null}
  • </>
  • ))}
  • <>
  • <Button
  • type="dashed"
  • onClick={() => add()}
  • style={{ width: '85%' }}
  • icon={<PlusOutlined />}
  • >
  • 添加手机号
  • </Button>
  • < errors={errors} />
  • </>
  • </>
  • )}
  • </>
  • </>
  • <>
  • <Button type="primary" htmlType="submit">
  • 提交
  • </Button>
  • </>
  • </Form>
  • </div>
  • );
  • };
  • export default FormGroup;