Antd 4 获取Form字段值
类组件获取表单字段值
由于Antd 4中去除了Form.create方法创建Form实例得到getFieldDecorator、validateFields等方法,我们使用类组件想要Form上的方法就需要用到Ref来获得实例。
import React, { Component } from 'react'
import { Form, Input, Button } from 'antd'
class Example extends Component {
formRef = React.createRef()
onFinish = values => {
console.log(values)
}
getValues= () => {
const form = this.formRef.current
const values = form.getFieldsValue(['name','age'])
console.log(values)
}
getValidateValues= async () => {
const form = this.formRef.current
try {
const values = await form.validateFields(['name','age'])
console.log(values)
} catch (err) {
console.log(err)
}
}
render() {
const { Item } = Form
return (
<Form ref={this.formRef} onFinish={this.onFinish}>
<Item name='name' label='姓名' rules={[{required:true,message:'请输入姓名'}]}>
<Input />
</Item>
<Item name='age' label='年龄'>
<Input />
</Item>
<Item>
<Button type='primary' htmlType='submit'>提交</Button>
<Button type='link' onClick={this.getValues}>非 Submit 方式(不验证)</Button>
<Button type='link' onClick={this.getValidateValues}>非 Submit 方式(验证)</Button>
</Item>
</Form>
)
}
}
export default Example
上诉就是Antd 4中怎么在类组件中获得表单组件的值,主要就是去除了Form.create后的一些变化。
补充
通过Ref获得实例后得到getFieldValue获取单个字段值、getFieldsValue获取多个字段值、validateFields获取验证后字段值等,使用这些方法主动去得到表单的值。
Form组件的onFinish属性绑定的方法,在触发表单提交的操作时会进行调用,并传入字段的值作为参数。这个方法会对表单的rules规则进行验证。
Form实例的getFieldValue和getFieldsValue方法获取表单的字段值时不会对rules规则进行验证。需要主动获取表单字段值并进行rules验证就需要用到validateFields方法,它的返回值时一个Promise对象。
版权声明:
Anand's Blog文章皆为站长Anand Zhang原创内容,转载请注明出处。
包括商业转载在内,注明下方要求的文章出处信息即可,无需联系站长授权。
请尊重他人劳动成果,用爱发电十分不易,谢谢!
请注明出处:
本文出自:Anand's Blog
本文永久链接:https://anandzhang.com/posts/frontend/10