import React, { useState, useEffect } from 'react'; import { Modal, Button, Form, Checkbox } from 'antd'; import { useForm } from 'antd/lib/form/Form'; interface ResourceSelectProps { form: ReturnType<typeof useForm>; } const ResourceSelect: React.FC<ResourceSelectProps> = ({ form }) => { const [modalVisible, setModalVisible] = useState(false); const [selectItem, setSelectItem] = useState<string[]>([]); const showModal = () => { setModalVisible(true); }; const handleOk = () => { form.setFieldsValue({ professionKnowledge: selectItem }); setModalVisible(false); }; const handleCancel = () => { setModalVisible(false); }; const handleCheckboxChange = (value: string) => { const updatedSelectItem = [...selectItem]; if (updatedSelectItem.includes(value)) { updatedSelectItem.splice(updatedSelectItem.indexOf(value), 1); } else { updatedSelectItem.push(value); } setSelectItem(updatedSelectItem); }; useEffect(() => { form.setFieldsValue({ professionKnowledge: selectItem }); }, [selectItem, form]); return ( <> <Form.Item label="涉及专业知识" name="professionKnowledge" rules={[{ required: true, message: '请选择涉及专业知识' }]} > <Button type="primary" onClick={showModal}> 选择资源 </Button> </Form.Item> <Modal title="选择资源" visible={modalVisible} onOk={handleOk} onCancel={handleCancel}> <Checkbox value="A" onChange={() => handleCheckboxChange('A')}> A </Checkbox> <Checkbox value="B" onChange={() => handleCheckboxChange('B')}> B </Checkbox> <Checkbox value="C" onChange={() => handleCheckboxChange('C')}> C </Checkbox> </Modal> </> ); }; export default ResourceSelect;
父组件
import React from 'react'; import { Form, Button, Space } from 'antd'; import ResourceSelect from './ResourceSelect'; const ParentForm: React.FC = () => { const [form] = Form.useForm(); const onFinish = async (values: any) => { // 在这里可以进行提交表单的操作 console.log('Form values:', values); }; const validateSelectItem = () => { // 自定义校验规则,检查是否选择了盒子 if (!form.getFieldValue('professionKnowledge')?.length) { return Promise.reject('请完成选择'); } return Promise.resolve(); }; return ( <Form form={form} onFinish={onFinish}> <ResourceSelect form={form} /> <Form.Item label="其他字段" name="otherField" rules={[{ required: true, message: '其他字段不能为空' }]} > <Input /> </Form.Item> <Form.Item label="创建场景" shouldUpdate rules={[{ validator: validateSelectItem }]} > {() => ( <Space> <Button type="primary" htmlType="submit"> 完成 </Button> </Space> )} </Form.Item> </Form> ); }; export default ParentForm;
标签:const,form,Form,selectItem,updatedSelectItem,demo,import From: https://www.cnblogs.com/cyanKoi/p/17922664.html