form表单组件问题

2020-07-14  本文已影响0人  米古月_f198

编辑弹窗,弹窗为父组件,编辑表单为子组件。 弹窗点击确认的时候,需要先得到表单的校验结果。即父组件需要调用子组件函数。
问题点:useRef 不能直接用于函数组件,需要export default forwardRef(TagForm)。

父组件代码

const Tag = (props)=>{
  const [loading,setLoading] = useState(false);
  const [rows,setRows] = useState([]);
  const [modalVisible,setModalVisible] = useState(false);
  const [editId,setEditId] = useState(null);
  const formRef = useRef();
  
  const handleShowModal = (editId)=>{
    setModalVisible(true);
    setEditId(editId);
  };

  const handleCloseModal = ()=>{
    setModalVisible(false);
    setEditId(null);
  };

  const handleDelete=(record)=>{
    Modal.confirm({
      title: '确定删除?',
      content: '删除标签',
      onOk() {
      },
      onCancel() {

      },
    });
  };

  const handleModalOK = ()=>{
    formRef.current.submit();
  };


  const columns = [{
    title: '名称',
    dataIndex: 'tagName',
    key: 'tagName',
  },{
    title: '操作',
    key:'id',
    width: 200,
    render: (text, record) => (
        <span>
            <a onClick={()=>handleShowModal(record.id)}>编辑</a>
            <Divider type="vertical"/>
            <a onClick={()=>handleDelete(record)}>删除</a>
        </span>
    )
  }];

  const titleEl = <div>
    <Button type={`primary`} onClick={()=>handleShowModal(null)} >新增标签</Button>
  </div>;

  return (<>
    <Table rowKey={`id`} title={()=>titleEl} columns={columns} dataSource={rows} loading={loading} pagination={false} />
    <Modal forceRender visible={modalVisible} title={(editId?`修改`:`新增`)} onOk={handleModalOK} onCancel={handleModalCancel}>
      <TagForm ref={formRef} editId={editId} />
    </Modal>
  </>)
};
export default Tag

子组件

import { Form, Input } from 'antd';
import React, {forwardRef, useEffect, useImperativeHandle} from 'react';

const TagForm = ({visible, editId, onCancel, onSuccess},tagFormRef)=>{

  const  [form]  = Form.useForm();
  const {getFieldDecorator, validateFields, resetFields, setFieldsValue} = form;

  useImperativeHandle(tagFormRef,()=>({

    submit:()=>{
      console.log("ss")
    }

  }));

  return <>
      <Form form={form} >
        <Form.Item label={`标签名称`} name={'tagName'}>
          <Input/>
        </Form.Item>
      </Form>
  </>

};
export default forwardRef(TagForm)
上一篇 下一篇

猜你喜欢

热点阅读