自学内容网 自学内容网

react hooks antd 父组件取子组件form表单的值

        在React中,父组件可以使用ref来访问子组件的方法或属性。子组件包含一个表单, 使用forwardRef、useImperativeHandle:forwardRef允许组件使用ref将 DOM 节点暴露给父组件,使用useImperativeHandle暴露方法给父组件。

        子组件:

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

const SubApp = (props, ref) => {
  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    formFields: form,
  }));

  return (
    <Form form={form} ref={ref} >
      ...
    </Form>
  );
};

export default forwardRef(SubApp);

        父组件:

import React, { useRef } from "react";
import { Button } from "antd";
import SubApp from "./subApp";

const FatherApp = () => {
  const formRef = useRef(null);

  // 查询按钮触发
  const query = () => {
    // 获取自定义条件form表单值
    if (formRef.current) {
      const { formFields } = formRef.current;
      // 首先进行表单校验
      formFields.validateFields().then(() => {
        const values = formFields.getFieldsValue();
        console.log(values);
      });
    }
  }

  return (
    <Button type= "primary" onClick = { query } > 查询 </Button>
    <SubApp ref = { formRef } />
  );
};

export default FatherApp;


原文地址:https://blog.csdn.net/u010234868/article/details/140352791

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!