简体   繁体   English

Ant design 4.0.1 - 从父组件访问类组件内部子窗体的方法

[英]Ant design 4.0.1 - Access methods of child form inside class component from parent component

After migrating from ant v3.x to v4.0.1 I can no longer access the methods of my child form from its parent component.从 ant v3.x 迁移到 v4.0.1 后,我无法再从其父组件访问我的子窗体的方法。

In version 3.x I could do something similar to the following:在版本 3.x 中,我可以执行类似于以下操作:

//Parent component - TestParent
import * as React from 'react';
import {createRef} from 'react';


export default class TestParent extends React.Component<{}, {}> {
  private formRef = createRef<any>();

  getFields = () => {
    const {form} = formRef.current.props;
    form.validateFields... ///etc
  }

  render() {
    return (
      <FormComponent
        wrappedComponentRef={this.formRef}
      />
      <Button onClick={() => {this.getFields()}>Button<Button/>
    );
  }
}


//Child component - FormComponent
import React from 'react';
import {Input, Form} from 'antd';

interface IProps {
  form: any;
}

class FormComponentContainer extends React.Component<Props, {}> {
   constructor(props: IProps) {
    super(props);
   }

  render() {
    const {form} = this.props;
    const {getFieldDecorator} = form;

    return (
      <Form>
        <Form.Item label="Full Name" colon={false}>
          {getFieldDecorator('name', {
            rules: [{required: true, message: 'Please enter your name'}]
          })(<Input placeholder="Please enter your name" />)}
        </Form.Item>
      </Form>
    );
  }
}

export const FormComponent: any = Form.create<Props>({
  name: 'form'
})(FormComponentContainer);

And I can access the child form fields using formRef .我可以使用formRef访问子表单字段。

However, since migrating to ant 4.0.1 I can no longer access the form fields, using the ref prop on the new Form component:但是,由于迁移到 ant 4.0.1,我无法再访问表单字段,使用新表单组件上的ref属性:

//Parent component - TestParent
import * as React from 'react';
import {createRef} from 'react';


export default class TestParent extends React.Component<{}, {}> {
  private formRef = createRef<any>();

  getFields = () => {
    const {form} = formRef.current.props;
    form.validateFields... ///etc
  }

  render() {
    return (
      <FormComponent
        formRef={this.formRef}
      />
      <Button onClick={() => {this.getFields()}>Button<Button/>
    );
  }
}


//Child component - FormComponent
import React from 'react';
import {Input, Form} from 'antd';

interface Props {
  formRef: any;
}

export default class FormComponentContainer extends React.Component<Props, {}> {
   constructor(props: Props) {
    super(props);
   }

  render() {
       return (
      <Form ref={this.props.formRef}>
        <Form.Item
          label="Full Name"
          colon={false} 
          name="name"
          rules={[{required: true, message: 'Please enter your name'}]}
        >
          <Input placeholder="Please enter your name" />
        </Form.Item>
      </Form>
    );
  }
}

Is there something I'm missing?有什么我想念的吗? Both the parent and the child need to be class components, as opposed to functional components.父组件和子组件都需要是类组件,而不是功能组件。

Not if this is in your final code,如果这是在您的最终代码中,则不会

but

formRef.current is already the form ref, formRef.current已经是表单引用,

so to use it should be just所以使用它应该只是

getFields = () => {
    const form = formRef.current;
    form.validateFields... ///etc
  }

see https://ant.design/components/form/#components-form-demo-control-refhttps://ant.design/components/form/#components-form-demo-control-ref

also if the only thing you want is to validate, you can use the new onFinish callback此外,如果您只想验证,则可以使用新的onFinish回调

I think you can use react ref forwarding ( https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components ) to solve your problem.我认为您可以使用 react ref forwarding ( https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components ) 来解决您的问题。

Here is a concrete example to show you how to use ref forwarding with antd:下面是一个具体的例子,向您展示如何在 antd 中使用 ref 转发:

Child component:子组件:

import { Form, Input } from 'antd'

const ChildComponent = React.forwardRef((props, ref) => (
  <Form ref={ref} layout="vertical" name="item">
    <Form.Item
      name="designation"
      label="designation"
      rules={[{ required: true, message: 'mandatory' }]}
    >
      <Input />
    </Form.Item>

    <Form.Item
      name="quantity"
      label="quantity"
      rules={[{ required: true, message: 'mandatory' }]}
    >
      <Input />
    </Form.Item>
    <Form.Item name="ean" label="ean">
      <Input />
    </Form.Item>
    <Form.Item
      name="sku"
      label="sku"
      rules={[{ required: true, message: 'mandatory' }]}
    >
      <Input />
    </Form.Item>
    <Form.Item
      name="price"
      label="price"
      rules={[
        {
          required: true,
          message: 'mandatory',
        },
      ]}
    >
      <Input />
    </Form.Item>
  </Form>
))

export default ChildComponent

ParentComponent:父组件:

import React, { useRef } from 'react'
import { Button } from 'antd'
import ChildComponent from './ChildComponent'

function ParentComponent() {
  const ref = useRef(null)

  function handleClick() {
    ref.current.validateFields().then(values => {
      console.log(values)
    })
  }

  return (
    <>
      <Button onClick={handleClick}>Validate</Button>
      <ChildComponent ref={ref} />
    </>
  )
}

export default ParentComponent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从子组件 Class 中的父组件访问道具? (专门针对 componentDidMount)? - How to access props from Parent Component inside the Child Class Component ? (specifically for componentDidMount)? 将表单值从子功能组件发送到父类组件 - send form values from child function component to parent class component 从子组件访问数据到父组件 - Access data from child component to parent component 从父组件访问子组件引用 - Access Child component reference from Parent Component 从reactjs中的父组件访问子组件 - access child component from parent component in reactjs 将React组件类实例传递给子组件以访问父代的变量和方法是否安全? - Is it safe to pass in React component class instance to child component to access to the parent's variables and methods? 如何访问子组件中的父组件方法,如下面的示例 - how to access parent component methods in child component like below example 如何从父 class 访问子组件的 state - How to access the state of a child component from a parent class 如何从无状态父级访问子 class 组件中的 function? - How to access a function in a child class component from a stateless parent? 不能使用 Ant 的 setFieldsValue class 组件的设计形式 - cannot use setFieldsValue of Ant Design Form of class component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM