根据官网给出的实例,可以通过useImperativeHandle
将子组件中props.form.getFieldsValue()
暴露给父组件,从而在父组件中就可以拿到表单值,代码如下:(注:代码只是作为方法示例,不作为可运行实例)
父组件
import React, {
useRef
} from 'react'
import { Modal } from 'antd'
import MyForm from './myForm'
const ParentComp = () => {
const getFormValue = useRef();
const handleOk = () => {
const fields = getFormValue.current.formFields;
console.log(fields)
}
return <Modal onOk={handleOk} >
<MyForm
wrappedComponentRef={getFormValue}
/>
</Modal>
}
export default ParentComp
子组件(myForm.jsx)
import React, { useImperativeHandle, useRef, forwardRef } from 'react'
import { Form } from 'antd'
const MyForm = (props, ref) => {
const formRef = useRef()
useImperativeHandle(ref, () => ({
formFields: props.form.getFieldsValue()
}))
return <Form ref={formRef}>
...
</Form>
}
const WrappedForm = Form.create({ name: 'form' })(forwardRef(MyForm))
export default WrappedForm