【CRR学习笔记】Antd之Modal内嵌Form,获取表单信息

7,732 阅读2分钟

ANTD

前端小菜默默从CSDN迁移到掘金。 这是第一篇文章

背景

需要弹出模态框Modal,填写Form表单后,点击Modal的确认按钮向后台提交或存储表单信息。

难点

  1. Form和Modal的Submit按钮是各自独立的;
  2. 获得填写表单数据

解决办法

1,在Modal中内嵌Form,并将属性通过props传递过去,将onSubmit统一为一个方法; 2,使用Form.create()封装,获得ref。注意被Modal封装后的ref变为wrappedComponentRef.

那么我们开始吧!

先看下Form组件的官方的属性和方法。

Form属性表格

1,Form.create()-它包装过的组件会自带 this.props.form 属性。

//使用方法
class YourForm extends Component{}
Form.create({})(YourForm);

this.props.form内含的API如下图:

this.props.form的API1
this.props.form的API2
我使用到的都标注了红框。

2,表单数据绑定-getFieldDecorator

getFieldDecorator注意点

getFieldDecorator(id, options)
//使用方法,例如
<FormItem>
  {getFieldDecorator('userName', {
    rules: [{ required: true, message: 'Please input your username!' }],
   })(
   <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
    )}
</FormItem>

getFieldDecorator的参数列表-1

getFieldDecorator的参数列表-2

3,渲染查询表单的查询条件-render <Form.Item>

Form.Item的参数列表-1

Form.Item的参数列表-2

4,获取查询条件的值- validateFields

使用方法:

const { validateFields } = this.props.form;
validateFields((errors, values) => {
  // ...
});
validateFields(['field1', 'field2'], (errors, values) => {
  // ...
});
validateFields(['field1', 'field2'], options, (errors, values) => {
  // ...
});

validateFields的参数列表

validateFields 的 callback 参数示例

errors:
{
  "username": {
    "errors": [
        {
        "message": "Please input your username!",
        "field": "username"
      }
    ]
  },
  "password": {
    "errors": [
      {
        "message": "Please input your Password!",
        "field": "password"
      }
    ]
  }
}
values:
{
  "username": "username",
  "password": "password",
}

!!看完上面的内容你可能有点会了,但是还会有点疑惑。 接下来我们来实际演示下: 首先创建组件WrappedForm:

class WrappedForm extends Component{
    render() {
        const { visible, onCancel, onOk, form, forEdit}= this.props;//这些属性和方法是在外面使用时传来的。
        const { getFieldDecorator } = form; //获取form属性的API
        return(
            <Modal
                visible={ visible }
                title= "新增组织结构"
                width={400}
                centered={ true }
                closable={ true }
                onOk={ onOk }//被点击确认调用onOk方法
                onCancel={ onCancel}
                footer={[
                    <Button key="back" onClick={ onCancel }>
                        取消
                    </Button>,
                    <Button key="submit" type="primary"  onClick={ onOk }>
                        提交
                    </Button>,
                ]}
            >
                <Form  className="modal-for-add"  >
                    <FormItem hideRequiredMark className='modal-for-name' label="名称">
                        {getFieldDecorator("username",{initialValue: ''})(
                            <Input
                                type="text"
                                style={{ width: 320 }}
                                placeholder= '请输入名称'
                                maxLength={20}
                            />
                        )}
                    </FormItem>
                   //...
                    <FormItem className='modal-for-description' label='描述'>
                        {getFieldDecorator("description",{
                            rules:[{required: true, message: 'Please input its description!' }]
                        })(
                            <TextArea rows={4}
                                      name='modal-description'
                                      autosize={{ minRows: 4, maxRows: 6 }}
                                      style={{ width: 320 }}

                            />
                        )}
                        {getFieldDecorator('description')(<Input type="textarea" />)}
                    </FormItem>
                </Form>
            </Modal>
        );
    }
}

export default WrappedForm;

在其他组件里调用:

const FormInModal = Form.create()(WrappedForm);//使用Form.create()包装。
//注意ref变为wrappedComponentRef.
<FormInModal
                    wrappedComponentRef={this.saveFormRef}
                    visible = {this.state.visible}
                    onCancel = {this.handleCancel}
                    onOk = {this.handleOk}
                    forEdit = {this.state.isEdit}
                />

//方法如下:
//将ref属性保存为this.formRef
 saveFormRef = (formRef) => {
        this.formRef = formRef;
};
//点击确认后处理表单数据
handleOk = () => {
        const { form } = this.formRef.props;//从ref中获得
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log('Received values of form: ', values);//这个values就是表单中的值
            if (this.handleValues(values)) {
               //
            }
        });
    };
    
handleValues =(values)=>{
        const Ele={};
        Ele.name = values.username;//values对象中就是getFieldDecorator绑定的FormITem的集合,values.id
        Ele.description = values.description;
        if (Ele.name!=null && Ele.description!=null){
          //
            return true;
        }else{
        //
            return false;
        }
    };
    

参考文献

juejin.cn/post/684490…

blog.csdn.net/ricky04187/…

ant.design/components/…