react antd 踩坑之Modal + Form

react antd 踩坑之Modal + Form

react 16.10.2
antd 4.3.0

一. antd Modal默认的ok按钮提交antd Form表单

  1. 隐藏modal footer,使用Form内嵌Button
<Form.Item> 
    <Button type="primary" onClick={onCheck}> Check </Button> 
</Form.Item>

2.对使用html的type属性以及form属性,代码如下

<Modal
    title="Basic Modal"
    visible={this.state.visible}
    onCancel={this.handleCancel}
    okButtonProps={{htmlType: 'submit', form: 'editForm'}}
>
    <Form
        id="editForm"
        layout="vertical"
        name="form_in_modal"
        onFinish={this.submitForm}
      >
    </Form>
</Modal>

3.直接使用form ref 的submit方法,代码如下

formRef = React.createRef();

handleModalOkClick = () => {
    formRef.submit();
}

<Modal
    title="Basic Modal"
    visible={this.state.visible}
    onCancel={this.handleCancel}
    onOk={this.handleModalOkClick}
>
    <Form
        form={formRef}
        layout="vertical"
        name="form_in_modal"
        onFinish={this.submitForm}
      >
    </Form>
</Modal>

二. 初始化Modal里表单数据

当Modal每次打开初始化数据不同时,需modal的 destroyOnClose 属性和Form initialValues 结合使用,否则数据一旦初始化后,不会更新

showModal = () => {
    this.setState({
        visible: true,
        values: {
            a: 111
        }
    });
};

<Button type="primary" onClick={this.showModal}>
    Open Modal
</Button>
<Modal
    title="Basic Modal"
    visible={this.state.visible}
    onCancel={this.handleCancel}
    onOk={this.handleModalOkClick}
    destroyOnClose
>
    <Form
        form={formRef}
        layout="vertical"
        name="form_in_modal"
        initialValues={this.state.values}
        onFinish={this.submitForm}
    >
    </Form>
</Modal>
阅读 80

推荐阅读