antd4 from拆分

期望一个新增页面,由多个表单构成,按钮提交统一校验

思路 需要把各个form实例保存下来,按钮提交时统一触发校验

父组件

<div className={styles.container}>
                <Form.Provider
                    onFormFinish={name => {
                        if (name === 'form1') {
                            // Do something...
                        }
                    }}
                >
                    <BaseInfoForm {...baseInfoProps}></BaseInfoForm>
                    <ProductInfo currentModel={currentModel} />
                    <AccessoriesInfo currentModel={currentModel} />
                    <OtherForm {...otherInfoProps}></OtherForm>
                </Form.Provider>
                <div className={styles.opsButtons}>
                    <Button
                        onClick={() => {
                            dispatch({
                                type: `${currentModel}/overrideStateProps`,
                                payload: {
                                    shouldRouterChange: false,
                                },
                            });
                            history.goBack();
                        }}
                    >
                        取消
                    </Button>
                    <Button type="primary" loading={loadState} onClick={() => handleSave(true)} htmlType="submit">
                        保存
                    </Button>
                </div>

子组件

import React, { useEffect, useRef } from 'react';
import { Input, Select, Form, Card, Col, Row, Radio } from 'antd';
import ContractBatchNumSelect from '@/components/ContractBatchNumSelect';
import NotSuitableForReturnAndExchange from '@/services/NotSuitableForReturnAndExchange';
import WorkOrdersClientSelect from './components/WorkOrdersClientSelect';
import styles from './index.less';

// 输入框最大字符数
export const INPUT_LENGTH_LIMIT = 50;
// 文本框最大字符数
export const TEXT_AREA_LENGTH_LIMIT = 500;
const whethertoshipStatusList = NotSuitableForReturnAndExchange.whethertoshipStatus();
const numberReg = /^[A-Za-z0-9]+$/;
const Option = Select.Option;
const FormItem = Form.Item;
const FormItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
};
const commonInputConfig = {
    maxLength: INPUT_LENGTH_LIMIT,
};
export default ({ currentModel, baseInfo, dispatch }) => {
    const [form] = Form.useForm();
    const { getFieldValue, setFieldsValue } = form;
    const formRef = useRef(null);
    useEffect(() => {
        formRef.current = form;
    }, [form]);
    useEffect(() => {
        dispatch({
            type: `${currentModel}/overrideStateProps`,
            payload: {
                baseForm: formRef,
            },
        });
    }, [dispatch, formRef, currentModel]);
    const handelChangeContractModel = choose => {
        if (choose) {
            const values = {
                client_id: choose.client_id,
                deliverdeliveryClientName: choose.delivery_client_name,
                delivery_client_id: choose.delivery_client_id,
                batch_contract_id: choose.id,
                contract_id: choose.admin_contract_id,
            };
            setFieldsValue({
                ...values,
            });
            dispatch({
                type: `${currentModel}/updateStateProps`,
                payload: {
                    name: 'baseInfo',
                    value: { ...values },
                },
            });
        }
    };
    const onValuesChange = (changedValues, allValues) => {
        const { dates, product_type, ...others } = allValues;
        const params = {
            ...others,
        };
        if (changedValues?.product_type) {
            dispatch({
                type: `${currentModel}/updateStateProps`,
                payload: {
                    name: 'baseInfo',
                    value: { product_id: '', product_type },
                },
            });
            setFieldsValue({
                product_id: '',
                product_type,
            });
        }
        dispatch({
            type: `${currentModel}/updateStateProps`,
            payload: {
                name: 'baseInfo',
                value: { ...params },
            },
        });
        dispatch({
            type: `${currentModel}/overrideStateProps`,
            payload: {
                shouldRouterChange: true,
            },
        });
    };
    return (
        <Form
            name="form2"
            form={form}
            initialValues={{
                client_name: '' || '',
                deliverdeliveryClientName: baseInfo?.deliverdeliveryClientName || '',
            }}
            onValuesChange={onValuesChange}
            {...FormItemLayout}
        >
            <Card title="基本信息" className={styles.card} bordered>
                <Row>
                    <Col span={12}>
                        <FormItem
                            name="client_id"
                            label="客户名称"
                            rules={[{ required: true, message: '请输入选择客户' }]}
                        >
                            {/* <Select
                                            showSearch
                                            allowClear
                                            filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                                            placeholder="请输入选择客户"
                                            // onChange={e => handelChangeClientsList(e)}
                                        >
                                            {clientsList?.map(ele => {
                                                return (
                                                    <Option key={ele.id} value={ele.id}>
                                                        {ele.name}
                                                    </Option>
                                                );
                                            })}
                                        </Select> */}
                            <WorkOrdersClientSelect placeholder="请输入选择客户" />
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem name="title" label="工单标题" rules={[{ required: true, message: '请输入工单标题' }]}>
                            <Input placeholder="请输入工单标题" {...commonInputConfig} />
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormItem
                            name="batch_contract_id"
                            label="合同编号"
                            rules={[{ required: true, message: '请选择合同编号' }]}
                        >
                            <ContractBatchNumSelect
                                onChangeContract={handelChangeContractModel}
                                form={form}
                                clientId={getFieldValue('client_id')}
                                placeholder="请选择合同编号"
                            />
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <FormItem name="deliverdeliveryClientName" label="发货客户">
                            <Input placeholder="选择合同自动带出" disabled />
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormItem
                            name="delivery_type"
                            label="发货类型"
                            rules={[{ required: true, message: '请选择发货类型' }]}
                        >
                            <Select
                                placeholder="请选择发货类型"
                                showSearch
                                allowClear
                                // disabled={pageType === 'update' && !isCreator && isReviewer}
                            >
                                {whethertoshipStatusList?.map(ele => {
                                    return (
                                        <Option key={ele.key} value={ele.key}>
                                            {ele.name}
                                        </Option>
                                    );
                                })}
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span={12}>
                        <Row>
                            <Col span={12}>
                                <FormItem
                                    name="sendBack"
                                    label="寄回运单号"
                                    labelCol={{
                                        xs: { span: 4 },
                                        sm: { span: 6 },
                                        md: { span: 6 },
                                        lg: { span: 6 },
                                    }}
                                    // wrapperCol={{ span: 20 }}
                                >
                                    <Radio.Group>
                                        <Radio value="back" style={{ whiteSpace: 'nowrap' }}>
                                            同城带回
                                        </Radio>
                                        <Radio value="sendBack" style={{ whiteSpace: 'nowrap' }}>
                                            寄回运单号
                                        </Radio>
                                    </Radio.Group>
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                {baseInfo?.sendBack === 'sendBack' ? (
                                    <FormItem
                                        labelCol={{
                                            xs: { span: 4 },
                                            sm: { span: 6 },
                                            md: { span: 6 },
                                            lg: { span: 6 },
                                        }}
                                        // wrapperCol={{ span: 20 }}
                                        name="send_back_waybill_number"
                                        label="申请编号"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入寄回运单号',
                                            },
                                            {
                                                pattern: numberReg,
                                                message: '只能填写字母或数字',
                                            },
                                        ]}
                                    >
                                        <Input placeholder="请输入寄回运单号" />
                                    </FormItem>
                                ) : null}
                            </Col>
                        </Row>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <FormItem
                            name="final_client"
                            label="最终客户"
                            rules={[
                                {
                                    required: getFieldValue('client_id') === 175,
                                    message: '请输入最终客户',
                                },
                            ]}
                        >
                            <Input placeholder="请输入最终客户" {...commonInputConfig} />
                        </FormItem>
                    </Col>
                </Row>
            </Card>
        </Form>
    );
};

validateFields 触发表单验证在这里插入图片描述

使用promise.all方法来提交实现:

  var p1 = new Promise((resolve, reject) => {
      console.log(1)
      resolve()
    })
    var p2 = new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log(2)
        resolve()
      }, 1000);
    })
    var p3 = new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log(3)
        resolve()
      }, 1000);
    })
 
    Promise.all([p1, p2, p3]).then((result) => {
      console.log("执行完毕");
    })

提交校验

    const handleSave = goBack => {
        const baseFormValidateFields = baseForm.current.validateFields();
        const otherFormValidateFields = otherForm.current.validateFields();
        Promise.all([baseFormValidateFields, otherFormValidateFields]).then(result => {
            console.log('执行完毕');
            dispatch({
                type: `${currentModel}/save`,
                payload: {
                    goBack,
                    callback: () => {
                        dispatch({
                            type: 'shipOrderList/getShipOrderList',
                        });
                    },
                },
            });
            dispatch({
                type: `${currentModel}/overrideStateProps`,
                payload: {
                    shouldRouterChange: false,
                },
            });
        });
    };
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值