首页 > 解决方案 > ReactJS: TypeError: this.ref.current.method is not an 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;

上面的代码显示了我的问题,两者都有相同的代码,但一个有效,另一个无效

这是子 A 组件:

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

这是子 B 组件:

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);

我试图调试this.Child_B.current

图像调试信息

我相信它显示了 Form.create() 数据并删除了我的数据我理解这一点,因为 Child_A 工作正常,唯一不同的是它没有 Form.create()

标签: reactjsantdant-design-pro

解决方案


这是因为Form.create()()它是一个返回另一个组件的高阶函数。

所以

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

DecoratedChild_B 可能有其他包装器,它变成这样:

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

这就是为什么你得不到你想要的。

要获取表单引用,您应该使用WrappedComponentRef

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

如果你想要一些自定义的东西,你必须为 ref func 使用其他名称


推荐阅读