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

antD4 表单重新封装时不能使用 setFieldsValue 方法。

错误:

this.formRef.current.setFieldsValue is not a function

通过 codesandbox 演示


凤凰求蛊
浏览 501回答 1
1回答

青春有我

antD4 表单重新封装时不能使用 setFieldsValue 方法。当您创建一个 Component 并将 anant Form放入其中时,您不应该期望它的行为就像 an Ant Form(因为您扩展了 a React Component,而不是 an Ant Form)。你需要setFieldsValue,所以你可以像这样实现它:import React, { PureComponent } from "react";import { Form as Component } from "antd";class Form extends PureComponent {&nbsp; formRef = React.createRef();&nbsp; render() {&nbsp; &nbsp; return <Component {...this.props} ref={this.formRef} />;&nbsp; }&nbsp; setFieldsValue(v) {&nbsp; &nbsp; this.formRef.current.setFieldsValue(v);&nbsp; }&nbsp; getForm() {&nbsp; &nbsp; return this.formRef.current;&nbsp; }}Form.Item = Component.Item;export default Form;所以你可以使用它:&nbsp; &nbsp; this.formRef.current.setFieldsValue({&nbsp; &nbsp; &nbsp; mobile: "110"&nbsp; &nbsp; });要么:&nbsp; &nbsp; this.formRef.current.getForm().setFieldsValue({&nbsp; &nbsp; &nbsp; mobile: "110"&nbsp; &nbsp; });codesandbox 上的演示
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript