antd Pro ProFormList外部控制增加删除

本文展示了如何在React应用中利用AntDesignPro的ProForm组件和useRef、useStatehooks创建动态表单。通过actionRef.current?.addOrremove实现外部按钮对表单行的增删操作,并通过ProFormList组件管理列表数据。此外,还涉及到了接口调用保存数据和错误处理。

通过外部按钮增加删除一行

官网文档:行为守卫
通过button 触发actionRef.current?.add or actionRef.current?.remove
在这里插入图片描述

import React, { useState, useRef, useEffect } from 'react';
import { Button, message, Modal, Space, Select, Divider, Form } from 'antd';
import {
  ProFormDigit,
  ProFormInstance,
  ProFormList,
  ProFormRadio,
  ProFormSelect,
} from '@ant-design/pro-form';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import type { FormListActionType } from '@ant-design/pro-form';
import { useModel, Access, useAccess } from 'umi';
import { organizationSave } from '@/services/ant-design-pro/tradingPlatformApi';
import {
  delegationDirectionEnum,
  operationTypeEnum,
  strategyNameEnum,
  ContractTypeEnum,
} from '@/constants/common';
import styles from '../../index.less';
import ProCard from '@ant-design/pro-card';

const CommitForm: React.FC<any> = (props) => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  // const { id = null, enable = false } = props.record;
  // console.log('props.record', props.record)
  const { type } = props;
  const formRef = useRef<ProFormInstance>();
  const [formList, setFormList] = useState([1]);
  const actionRef = useRef<
    FormListActionType<{
      name: string;
    }>
  >();

  const handleConfirm = async (values: any) => {
    const apiParams = {
      id: null,
      comment: values.comment,
      name: values.name,
      type,
    };
    const res = await organizationSave(apiParams);
    if (res.flag) {
      // formRef?.current?.resetFields();
      // props.query();
      message.error('申请成功!');
    } else {
      message.error('添加失败');
    }
  };

  const formItemLayout = {
    labelCol: { style: { width: 100 } },
    wrapperCol: { style: { width: 240 } },
  };

  return (
    <>
      <ProForm<{
        name: string;
        company: string;
      }>
        layout="horizontal"
        autoFocusFirstInput
        labelCol={{ style: { width: 100 } }}
        wrapperCol={{ style: { width: 240 } }}
        // submitTimeout={2000}
        formRef={formRef}
        onFinish={async (values) => {
          // 接口
          console.log('values :>> ', values);
          // await handleConfirm(values);
        }}
        initialValues={{
          total: 1,
        }}
      >
        <Divider
          style={{
            marginTop: -6,
            marginBottom: 18,
          }}
        />
        <ProForm.Group>
          <ProFormSelect
            name="comment"
            valueEnum={strategyNameEnum}
            label="名称"
            placeholder="请输入"
          />
        </ProForm.Group>
        <ProForm.Group>
          {/* <ProFormDigit
            name="total"
            min={1}
            max={10}
            fieldProps={{
              precision: 0,
              readOnly: true,
              onStep: (value, info) => {
                console.log(111, value, info.type);
                if (info.type === 'up') {
                  const list = actionRef.current?.getList();
                  actionRef.current?.add({
                    name: '新增' + list?.length,
                  });
                } else {
                  actionRef.current?.remove(1);
                }
              },
            }}
            label="增&减"
            placeholder="请输入"
          /> */}
          <Form.Item label="增&减" name="total">
            <Space>
              <Button
                type="default"
                size="small"
                shape="circle"
                onClick={() => {
                  if (formList.length === 10) {
                    return;
                  }
                  // const list = actionRef.current?.getList();
                  actionRef.current?.add(1);
                  setFormList([...formList, 1]);
                }}
                icon={<PlusOutlined />}
              />
              {formList.length}
              <Button
                type="default"
                size="small"
                shape="circle"
                onClick={() => {
                  if (formList.length === 1) {
                    return;
                  }
                  const newArr = formList.splice(1);
                  actionRef.current?.remove(1);
                  setFormList(newArr);
                }}
                icon={<MinusOutlined />}
              />
            </Space>
          </Form.Item>
        </ProForm.Group>
        <Divider
          style={{
            marginTop: -6,
            marginBottom: 18,
          }}
        />
        <ProFormList
          name={['records']}
          initialValue={formList}
          // creatorButtonProps={{
          //   position: 'top',
          // }}
          creatorButtonProps={false}
          actionRender={(props, action) => {
            return [];
          }}
          actionRef={actionRef}
        >
          {/* {listDom} */}
          <ProCard
            bordered
            style={{
              marginBottom: 8,
              position: 'relative',
            }}
          >
            <ProForm.Group>
              <ProFormDigit
                name="name"
                label="价格"
                min={0}
                rules={[{ required: true }]}
                placeholder="请填入"
                {...formItemLayout}
              />
              <ProFormDigit
                name="comment"
                min={0}
                label="委托数量"
                placeholder="请输入"
                {...formItemLayout}
              />
            </ProForm.Group>
          </ProCard>
        </ProFormList>
      </ProForm>
    </>
  );
};

export default CommitForm;

Ant Design Pro 的 `ProFormList` 组件中,**隐藏新建一行的操作按钮**(即“添加”按钮)可以通过以下方法实现: --- ### **方法 1:使用 `actionRender` 隐藏按钮** `ProFormList` 的 `actionRender` 属性允许自定义操作按钮的渲染。通过返回 `null` 或空内容,可以隐藏默认的“添加”按钮。 #### **示例代码** ```tsx import { ProForm, ProFormText, ProFormList } from '@ant-design/pro-components'; export default () => ( <ProForm> <ProFormList name="users" label="用户列表" actionRender={() => null} // 隐藏操作按钮 > {(field, index, action) => ( <ProFormText name={[index, 'name']} label="姓名" placeholder="请输入姓名" /> )} </ProFormList> </ProForm> ); ``` #### **关键点** - `actionRender={() => null}` 直接隐藏操作按钮区域。 - 如果需要保留删除按钮,可以在 `actionRender` 中单独渲染删除按钮(见方法 2)。 --- ### **方法 2:自定义 `actionRender` 仅保留删除按钮** 如果希望保留删除按钮但隐藏“添加”按钮,可以通过 `actionRender` 手动控制。 #### **示例代码** ```tsx <ProFormList name="users" label="用户列表" actionRender={(field, action) => [ // 只渲染删除按钮,不渲染添加按钮 action.remove, ]} > {(field, index, action) => ( <ProFormText name={[index, 'name']} label="姓名" /> )} </ProFormList> ``` #### **关键点** - `actionRender` 返回一个数组,包含需要显示的操作按钮(如 `action.remove`)。 - 默认情况下,`ProFormList` 会渲染 `action.add`(添加按钮)和 `action.remove`(删除按钮)。 --- ### **方法 3:通过 `copyIconProps` 和 `deleteIconProps` 控制** 如果需要更细粒度的控制(例如禁用按钮而非隐藏),可以使用 `copyIconProps` 和 `deleteIconProps`: ```tsx <ProFormList name="users" label="用户列表" copyIconProps={false} // 隐藏复制按钮 deleteIconProps={false} // 隐藏删除按钮 // 如果完全隐藏操作列,可以结合 actionRender={() => null} > {(field, index) => ( <ProFormText name={[index, 'name']} label="姓名" /> )} </ProFormList> ``` #### **注意** - `copyIconProps={false}` 和 `deleteIconProps={false}` 仅隐藏图标,但不会完全移除操作列。 - 如果需要彻底隐藏操作列,仍需结合 `actionRender={() => null}`。 --- ### **方法 4:通过 CSS 隐藏按钮(不推荐)** 如果上述方法不满足需求,可以通过 CSS 强制隐藏按钮: ```tsx <ProFormList name="users" label="用户列表" className="hide-add-button" > {(field, index) => ( <ProFormText name={[index, 'name']} label="姓名" /> )} </ProFormList> <style> .hide-add-button .ant-form-list-action { display: none; } </style> ``` #### **缺点** - 依赖 CSS 选择器,可能因 Ant Design 版本更新失效。 - 不推荐作为首选方案。 --- ### **总结** | 需求 | 推荐方法 | |------|----------| | **完全隐藏操作按钮** | `actionRender={() => null}` | | **仅保留删除按钮** | `actionRender={(field, action) => [action.remove]}` | | **禁用按钮而非隐藏** | `copyIconProps={false} + deleteIconProps={false}` | | **强制隐藏(应急方案)** | CSS 选择器(如 `.ant-form-list-action { display: none }`) | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值