Ant Design 表单中getFieldDecorator、getFieldValue、setFieldValue用法

一、getFieldDecorator和v-decorator

这里先说一下v-decorator指令:

下面是form表单内的文本输入框,使用了v-decorate进行数据绑定:

<a-form layout="inline" :form="form">
	<a-form-item label="名称:">
	  <a-input placeholder="请输入名称" v-decorator="['name', { rules: [{ required: true, message: '请输入名称!' }] }]"></a-input>
	</a-form-item>
</a-form>

这里使用的template语法,form必须在data内定义:

form: this.$form.createForm(this),

这个是v-decorate的用法,类似于v-model,但是v-decorator可以更方便的添加校验,必填项等;v-model可以更方便地获取值以及设置值,这个是二者在开发时最明显的区别。

form设置值当对form值进行定义后,后面就可以使用this.form来获取表单内的东西了。如

this.form.resetFields();//重置
this.form.setFieldsValue({'name':' '});//设置name的值
//或
this.$nextTick(() => {
  this.form.setFieldsValue(pick(this.model, ',name', 'age'))
});

getFieldDecorator 是一个方法,这个方法接收两个参数,第一个是表单的字段对象,第二个是验证规则。这个方法本身返回一个方法,需要将需要获取值的标签包裹进去。

<From>
  <FormItem>
      //JS代码书写时需要用 { } 包裹起来,不能直接写在代码块中  
      {
          getFieldDecorator('userName',{
            initialValue:'Jack',
             rules:[]
             })(
                    <Input placeholder='请输入用户名'/>
                )
        }
  </FormItem>
</From>

第一个参数是用户自定义的、用于识别该控件的变量名,这样便于在获取或设置该控件的值。
值得注意的是,getFieldDecorator是一个非常智能的方法,它可以获得自定义组件的value值,在提交表单时会很方便。其次,initialValue的值会覆盖子组件中的placeHolder,如果子组件是下拉框,也会根据initialValue的值来匹配自己的value,并显示相应的值,可以说非常智能了。

二、getFieldValue

  handleSubmit = e => {
    const { dispatch } = this.props;
    e.preventDefault();
    var date_juban = this.props.form.getFieldValue('date_juban');
    this.state.open_time_start = date_juban[0];
    this.state.open_time_end = date_juban[1];
    if (this.refs.pics.state.fileList.length > 0)
      this.state.image = this.refs.pics.state.fileList[0].response.url;
    this.state.location_longitude = this.props.form.getFieldValue('location_longitude');
    this.state.location_latitude = this.props.form.getFieldValue('location_latitude');
    }

在提交表单或是与后端交互时,如果需要一个控件的值,那么就用this.props.form.getFieldValue(‘变量名’)的方式进行获取,注意:‘变量名’这个参数只能由getFieldDecorator所设定的。

注意:getFieldValue不能获取没有使用getFieldDecorator绑定的控件(即:如果控件值标注了id属性,用这个方法无效)。应使用document.getElementById(“id名”).value的方式进行获取值。

三、setFieldValue

<FormItem {...formItemLayout} label={<span>地图</span>}>
              <AMapModule
                lng={''}
                lat={''}
                address={getFieldValue('position')}
                getMapPoint={point => {
                  setFieldsValue({
                    location_latitude: point.lat,
                    location_longitude: point.lng,
                  });
                }}
                getMapAddress={address => {
                  setFieldsValue({
                    position: address,
                  });
                }}
              />
            </FormItem>
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐