import React, { useEffect } from 'react'; import { Modal, Form, Button, Input, Space } from 'antd'; import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'; const ParmarModal = props => { const { pageUrl, visible, handleCancel, parmarCallBack } = props; const [form] = Form.useForm(); useEffect(() => { if (visible) { // 给url通过字符串分割成表单需要的数据形式 let parma = pageUrl .split('|')[1] ?.split('&') ?.map(item => ({ key: item.split('=')[0], value: item.split('=')[1] })); form.setFieldsValue({ parmars: parma }); } else { // 关闭弹窗清除表单数据 form.resetFields(); } }, [visible]); // 保存 const onFinish = () => { form.validateFields().then(validate => { if (validate) { let parma = form .getFieldValue('parmars') ?.map(item => `${item.key}=${item.value}`) .join('&'); console.log(parma, 'parma'); if (parma) { parmarCallBack(`${pageUrl.split('|')[0]}|${parma}`); } else { parmarCallBack(`${pageUrl.split('|')[0]}`); } } }); }; return ( <div> <Modal title="参数配置" visible={visible} onOk={onFinish} onCancel={handleCancel} maskClosable={false} destroyOnClose centered > <div style={{ maxHeight: '400px', overflowY: 'scroll', marginBottom: '10px' }}> <Form name="form" form={form} labelCol={{ span: 7 }}> <Form.List name="parmars"> {(fields, { add, remove }) => ( <> {fields.map(({ key, name, fieldKey, ...restField }) => ( <Space key={key} style={{ display: 'flex', marginBottom: 8, justifyContent: 'center' }} align="baseline" > <Form.Item {...restField} name={[name, 'key']} fieldKey={[fieldKey, 'key']} validateTrigger={['onChange', 'onBlur']} rules={[ { required: true, message: '请填写参数名' }, { validator: () => { // 验证参数名不能重复 const allKey = form .getFieldsValue() .parmars.map(item => (item ? item.key : '')); const repeatKey = new Set(allKey); if (repeatKey.size !== allKey.length) { return Promise.reject(new Error('参数名重复')); } return Promise.resolve(); }, }, ]} > <Input placeholder="请填写参数名" /> </Form.Item> <Form.Item {...restField} name={[name, 'value']} fieldKey={[fieldKey, 'value']} rules={[{ required: true, message: '请填写参数' }]} > <Input placeholder="请填写参数" /> </Form.Item> <MinusCircleOutlined onClick={() => remove(name)} style={{ marginLeft: '10px', fontSize: '20px' }} /> </Space> ))} <Form.Item> <Button style={{ width: '375px', marginLeft: '30px' }} type="dashed" onClick={() => add()} block icon={<PlusOutlined />} > 添加参数 </Button> </Form.Item> </> )} </Form.List> </Form> </div> </Modal> </div> ); }; export default ParmarModal;