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

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

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

第二个参数是options,不一样的配置能够完成更多的任务,例如必填数据验证java

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

也能够完成更多业务逻辑数据验证,例如:antd

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

还能够指定一个初始值:async

{
    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
相关文章
相关标签/搜索