简体   繁体   English

antD4表单重新封装时无法使用setFieldsValue方法

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

The setFieldsValue method cannot be used when the antD4 form is reencapsulated.对antD4表单进行重新封装时,不能使用setFieldsValue方法。

Error:错误:

this.formRef.current.setFieldsValue is not a function

Demo by codesandbox代码沙盒演示

The setFieldsValue method cannot be used when the antD4 form is reencapsulated.对antD4表单进行重新封装时,不能使用setFieldsValue方法。

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 ).当您创建一个组件并将ant Form放入其中时,您不应期望它的行为就像Ant Form (因为您扩展了React Component ,而不是Ant Form )。 you need setFieldsValue , so you can implement it like:你需要setFieldsValue ,所以你可以像这样实现它:

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 代码沙盒演示

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM