使用钩子函数:

import React, { useState } from 'react';
import {
  Form,
  FormItem,
  FormButtonGroup,
  Submit,
  Reset,
  Input,
} from '@formily/antd';
import { Field } from '@formily/react';
import { createForm } from '@formily/core';
import { Button } from '@alifd/next';

// 封装钩子函数
const useAddRemoveElement = () => {
  const [list, setList] = useState([]);

  const addElement = (value: any) => {
    setList([...list, value]);
  };

  const removeElement = (index: any) => {
    if (index >= 0 && index < list.length) {
      const updatedList = [...list];
      updatedList.splice(index, 1);
      // updatedList.pop();
      setList(updatedList);
    } else {
      console.log('无法移除');
    }
  };

  return {
    list,
    addElement,
    removeElement,
  };
};

// 在组件中使用该钩子函数
const FormilyForm: React.FC<FormilyFormProps> = (props: any) => {
  const { list, addElementInput, addElementSelect, removeElement } = useAddRemoveElement();
  const form = createForm();

  const handleAdd = () => {
    addElement(
      <div>
        <Field
          key={`${list.map((item, index) => {
            return index;
          })}`}
          name='aaa'
          title='测试表单项'
          required
          decorator={[FormItem]}
          component={[Input]}
        />
      </div>,
    );
  };

  return (
    <>
      <Form form={form}>
        {list.map((item, index) => (
          <div>
            {item}
            <Button
              onClick={() => removeElement(index)}
            >
              移除
            </Button>
          </div>
        ))}
        <FormButtonGroup.FormItem>
          <Button
            onClick={() => handleAdd()}
          >
            添加
          </Button>
          <Submit onSubmit={console.log}>提交</Submit>
          <Reset>重置</Reset>
        </FormButtonGroup.FormItem>
      </Form>
    </>
  );
};

export default FormilyForm;

效果:类似ahooks的useDynamicList。以上代码中,点击添加,添加一个表单项,点击移除,移除对应的表单项。

06-27 21:10