【问题标题】:ReactJS: TypeError: this.ref.current.method is not a function with ant design formReactJS: TypeError: this.ref.current.method is not an function with ant design form
【发布时间】:2019-07-01 22:05:46
【问题描述】:
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

image debug info

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

【问题讨论】:

    标签: reactjs antd ant-design-pro


    【解决方案1】:

    这是因为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 使用其他名称

    【讨论】:

    • render = () =&gt; &lt;div&gt; &lt;Child_A ref={this.Child_A}/&gt; &lt;Child_B wrappedComponentRef={form =&gt; this.Child_B = form}/&gt; &lt;/div&gt; 谢谢解决
    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 2022-06-30
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多