说明

此文是为了记录观看视频谷粒后台中AntD3与当前AntD4部分写法的差异。

Form表单

官方迁移说明:https://ant.design/components/form/v3-cn/

在AntD4中表单的submit事件被替换成了onFinish

获取表单实例

通过为Form组件绑定属性ref即可。每个Form.Item组件中的name属性代表当前表单的字段。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<Form
name='normal_login'
className='login-form'
// 为表单添加引用
ref={this.formRef}
// 为表单添加校检完成的事件
onFinish={this.handleSubmit}
>
<Form.Item
name='username'
rules={[
{ required: true, message: 'Please input your username!' }
]}
>
<Input
prefix={
<UserOutlined
className='site-form-item-icon'
style={{ color: 'rgba(0,0,0,.25)' }}
/>
}
placeholder='Username'
/>
</Form.Item>
<Form.Item>
<Button
type='primary'
htmlType='submit'
className='login-form-button'
>
登录
</Button>
</Form.Item>
</Form>

通过事件获取

1
2
3
4
5
6
7
8
9
10
11
12
export default class Login extends Component {
// 创建表单实例
formRef = React.createRef()
// 表单提交事件
handleSubmit = () => {
console.log(this.formRef.current)
// 调用 getFieldValue 方法获取Form.Item.name 的值 (即username和password)
const { getFieldValue } = this.formRef.current
const { username, password } = getFieldValue()
console.log(username, password)
}
}

image-20201116152444101

自定义验证规则

AntD4中已经没有callback回调函数了,而是返回Promise对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 自定义验证-密码
// AntD4中已经没有callback回调函数了,而是返回Promise对象
validatePwd = (rule, value) => {
// value 表示当前输入框传入的值
console.log(rule, value)
if (!value) {
return Promise.reject('密码必须输入')
} else if (value.length < 5) {
return Promise.reject('密码长度不能小于4')
} else if (value.length > 12) {
return Promise.reject('密码长度不能大于12')
} else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
return Promise.reject('密码必须是大写字母、小写字母或下划线组成')
} else {
return Promise.resolve()
}
}

表单统一验证

新版直接使用 onFinish 事件,该事件仅当校验通过后才会执行。

1
2
3
4
<Form.Item
name='password'
rules={[{ validator: this.validatePwd }]}
></Form.Item>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 自定义验证-密码
// AntD4中已经没有callback回调函数了,而是返回Promise对象
validatePwd = (rule, value) => {
// value 表示当前输入框传入的值
console.log(rule, value)
if (!value) {
return Promise.reject('密码必须输入')
} else if (value.length < 5) {
return Promise.reject('密码长度不能小于4')
} else if (value.length > 12) {
return Promise.reject('密码长度不能大于12')
} else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
return Promise.reject('密码必须是大写字母、小写字母或下划线组成')
} else {
return Promise.resolve()
}
}