需求:利用antd框架的对话框,实现表单的提交
场景:表格的增加纪录
解决思路:在Modal组件里面增加form组件,对form组件增加ref属性,拿到form对象,进而得到需要提交的数据
代码:
import React, { Component } from 'react';
import { Modal } from 'antd';
import WrappedNormalLoginForm from './FormDemo';
//Modal代码
class ModalDemo extends Component {
state = {
ModalText: 'Content of the modal',
visible: true,
confirmLoading: false,
}
handleOk = (e) => {//点击对话框OK按钮触发的事件
console.log();
this.setState({
ModalText: 'The modal will be closed after two seconds',
confirmLoading: false,
visible:true
});//上面的代码可以忽略
let demo=this.refs.getFormVlaue;//通过refs属性可以获得对话框内form对象
demo.validateFields((err, values) => {
if(!err){
console.log(values);//这里可以拿到数据
}
});
}
handleCancel = () => {//点击取消按钮触发的事件
console.log('Clicked cancel button');
this.setState({
visible: false,
});
}
render() {
const { visible, confirmLoading, ModalText } = this.state;
return (
<div>
<Modal title="Title"
visible={visible}
onOk={this.handleOk}
confirmLoading={confirmLoading}
onCancel={this.handleCancel}
>
<WrappedNormalLoginForm ref="getFormVlaue" />//增加ref属性,目的是获得form对象
</Modal>
</div>
);
}
}
export default ModalDemo;
import React, { Component } from 'react';
import { Form, Icon, Input, Button, Checkbox } from 'antd';
const FormItem = Form.Item;
//form代码,没有什么改进,把下面的提交按钮去掉就行
class NormalLoginForm extends Component {
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form className="login-form">
<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>
<FormItem>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }],
})(
<Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
)}
</FormItem>
</Form>
);
}
}
const WrappedNormalLoginForm = Form.create()(NormalLoginForm);
export default WrappedNormalLoginForm;
实现效果:
名称解释:antd-ant design