Ant design pro 开发笔记 - 表单和数据绑定

antd支持表单双向绑定,开发过程中无需通过onChange()回调函数去获取组件的值,通过 getFieldDecorator() 可以自动完成数据绑定的功能。

{
    getFieldDecorator('email', {})(<Input />)
}

第二个参数是options,不同的配置可以完成更多的任务,例如必填数据验证

{
    let opt = { rules: [ { required: true, message: "the field must supply." } ] }
    getFieldDecorator('email', opt)(<Input />)
}

也可以完成更多业务逻辑数据验证,例如:

{
    let opt = { rules: [ { type: 'email', message: "It's invalid email address." } ] }
    getFieldDecorator('email', opt)(<Input />)
}

还可以指定一个初始值:

{
    let opt = { initialValue: 'hello@mail.com' }
    getFieldDecorator('email', opt)(<Input />)
}
注意:通过initialValue指定的初始值,只在第一次render()中起作用。如果我们通过API获取了数据之后,表单数据不会发生变化。
这个时候就要用到mapPropsToFields()来为字段绑定数据。
{
    function mapModelToProps(model) {
      return {
        item: model.requirement.item,
        loading: model.loading.effects['requirement/fetch']
      };
    }
    function mapPropsToFields(props) {
      return {
        description: Form.createFormField({
          value: props.item.description
        })
      }
    }
    export default connect(mapModelToProps)(Form.create({mapPropsToFields})(Edit));
}

这里有两个函数来map所需要的数据:

  1. mapModelToProps()将state中所需要的数据映射到props上。
  2. mapPropsToFields()则将props中的数据映射到表单字段上,并更新字段的value值。注意使用这个函数必须用Form.createFormField()封装需要绑定的字段。
Ant design使用的表单组件是rc-form
使用的验证组件是async-validator

评论

暂无评论