• ant design form动态增减表单项Form.List如何进行动态校验规则


            项目需求:

            在使用ant design form动态增减表单项Form.List时,Form.List中有多组表单项,一组中的最后一个表单项的校验规则是动态的,该组为最后一组时,最后一个表单项是非必填项,其他时候为必填项。假设动态增加了两组表单项,均为填写内容,在必填项校验被触发后,删除了第二组表单项,此时仅剩一组表单项,想要最后一个表单项的校验状态不再显示必填项提示。如下图所示:

    想要的效果,最后一个表单项不显示必填项提示:       

            解决思路:

            使用动态校验规则,获取到最后一组的索引,使用form.validateFields重新触发校验规则。

            代码如下:

    1. import React, { useState } from 'react';
    2. import { Form } from 'antd';
    3. const App = () => {
    4. const [lastIndex, setLastIndex] = useState(false); // form表单最后一组数据的索引
    5. const [form] = Form.useForm();
    6. useEffect(() => {
    7. // 减少表单项时,重新触发表单验证,使form最后一组中最后一个表单项的验证状态不再显示必填项提示
    8. form.validateFields([['configs', lastIndex, 'lastFormOption']]);
    9. }, [lastIndex, form]);
    10. return (
    11. <Form form={form} initialValues={{ configs: [{}] }} >
    12. ……
    13. <Form.List name="configs">
    14. {(fields, { add, remove }) => (
    15. <>
    16. {fields.map(({ key, name, ...restField }, index) => {
    17. // 这里获取最后一组表单项索引
    18. setLastIndex(fields.length - 1);
    19. return (
    20. <Row
    21. key={key}
    22. >
    23. ……
    24. <Col span={5}>
    25. <Form.Item
    26. {...restField}
    27. name={[name, 'lastFormOption']}
    28. rules={[
    29. {
    30. required: (fields.length - 1) == index ? false : true,
    31. message: '请选择……',
    32. },
    33. ]}
    34. >
    35. <Select
    36. options={options}
    37. disabled={(fields.length - 1) == index}
    38. placeholder="最后一条自定义条件为非必填项"
    39. />
    40. Form.Item>
    41. Col>
    42. <Col span={2}>
    43. <MinusCircleOutlined onClick={() => remove(name)} />
    44. Col>
    45. Row>
    46. )
    47. })}
    48. <Form.Item >
    49. <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
    50. 新增
    51. Button>
    52. Form.Item>
    53. )}
    54. Form.List>
    55. Form>
    56. );
    57. };
    58. export default App;

            上述解决方式中,如果App作为一个子组件用到了ForwardRef,会出现下面的告警:

            Warning: Cannot update a component (`ForwardRef(AddRemoveFormItems)`) while rendering a different component (`Field`). To locate the bad setState() call inside `Field`, follow the stack trace as described……

            解决方案:去掉setLastIndex(fields.length - 1);等相关代码,将规则校验放在删除表单组的操作中。代码如下:

    1. <MinusCircleOutlined style={{ fontSize: 24 }} onClick={() => {
    2. remove(name);
    3. form.validateFields();
    4. }} />

  • 相关阅读:
    9、多媒体基础知识
    【Vue】首屏加载优化
    MySQL-SQL语言
    Java 终极学习路线 - 共计 9 大模块 /6 大框架 /13 个中间件
    C和C++关键字
    Python 多进程编程《*》:shared_memory 模块
    UVaLive 6693 Flow Game (计算几何,线段相交)
    2022年五款适合新手入门的吉他推荐,超全面吉他选购攻略防雷不踩坑!
    使用反射调用私有内部类方法
    mysql函数汇总之系统信息函数
  • 原文地址:https://blog.csdn.net/u010234868/article/details/140377619