Search code examples
reactjsantdant-design-pro

ReactJS: TypeError: this.ref.current.method is not a function with ant design form


class Parent extends Component {

    constructor(props) {
        super(props);
        this.Child_A = React.createRef();  
        this.Child_B = React.createRef();
    }

    function_uses_Child_A = ()=> {
        // This is working fine
        this.Child_A.current.Child_A_Function()
    }

    function_uses_Child_B = ()=> {
        // This is Does NOT work
        // this.Child_A.current.Child_B_Function() is not a function 
        this.Child_A.current.Child_B_Function()
    }

    render() {
        return (
            <div>
                <Child_A ref={this.Child_A}/>
                <Child_B ref={this.Child_B}/>   
            </div>
        );
    }
}
export default Parent;

The above code shows my problem where both has the same code but one works and the other doesn't

This is Child A component:

class Child_A extends Component {
    Child_A_Function = () => "Working";
    render = () => <h1>Child_A</h1>
}
export default Child_A;

This is Child B component:

import {Form} from "antd";

class Child_B extends Component {
    Child_B_Function = () => "Not Working";
    render = () => <h1>Child_B</h1>
}
export default Form.create()(Child_B);

I tried to debug this.Child_B.current

image debug info

I believe it shows the Form.create() data and removing mine I understand this because Child_A works fine and the only different is it doesn't have Form.create()


Solution

  • This is because Form.create()() is a higher order function which returns another component.

    so

    const DecoratedChild_B = Form.create()(Child_B);
    

    DecoratedChild_B may have other wrapper around it, and it become like this:

    <wrapper ref={this.Child_B}>
       <Child_B/>
    </wrapper>
    

    That's why you don't get what you want.

    to get form ref you should use wrappedComponentRef

    const EnhancedForm = createForm()(Form);
    <EnhancedForm wrappedComponentRef={(inst) => this.formRef = inst} />
    this.formRef // => The instance of Form
    

    if you want something custom, you have to use other name for the ref func