Search code examples
javascriptreactjsant-design-pro

The setFieldsValue method cannot be used when the antD4 form is reencapsulated


The setFieldsValue method cannot be used when the antD4 form is reencapsulated.

Error:

this.formRef.current.setFieldsValue is not a function

Demo by codesandbox


Solution

  • The setFieldsValue method cannot be used when the antD4 form is reencapsulated.

    when you create a Component and put an ant Form in it, you shouldn't expect it to behave just like an Ant Form (since you extends a React Component, not an Ant Form). you need setFieldsValue, so you can implement it like:

    import React, { PureComponent } from "react";
    import { Form as Component } from "antd";
    
    class Form extends PureComponent {
      formRef = React.createRef();
    
      render() {
        return <Component {...this.props} ref={this.formRef} />;
      }
      setFieldsValue(v) {
        this.formRef.current.setFieldsValue(v);
      }
      getForm() {
        return this.formRef.current;
      }
    }
    
    Form.Item = Component.Item;
    export default Form;
    
    

    So you can use it with:

        this.formRef.current.setFieldsValue({
          mobile: "110"
        });
    

    Or:

        this.formRef.current.getForm().setFieldsValue({
          mobile: "110"
        });
    

    Demo on codesandbox