React+AntDesign结合Table、Modal+Form的使用
最近写React + AntDesign时,使用到Modal和Form组件时候,因为Modal组件自带onOk按钮,因此不能使用Form自带的onFinish函数进行表单验证,查了查资料,大致了解是通过使用 ref 的方式获得表单值甚至可以发起表单校验方法。不多说了,直接上代码。
export default class App extends Component {
formRef=React.createRef();
state={
categoryList:[], //商品分类列表
isModalVisible:false, //控制弹窗的展示或隐藏
operType:'', //操作类型(新增?修改?)
}
//弹出商品分类,作为添加
showAdd=()=>{
this.setState(()=>{
return({operType:'add',isModalVisible:true})
});
}
//弹出商品分类,作为修改
showUpdate=(item)=>{
this.setState(()=>{
return({operType:'update',isModalVisible:true})
});
this.formRef.current.setFieldsValue({categoryName:item.categoryName})
}
//弹出框确定的回调
handleOk=()=>{
const {operType}=this.state;
//Modal中表单验证回调
this.formRef.current.validateFields().then(values=>{
// if(operType==='add'){
// this.toAdd(values);
// }else{
// }
this.setState(()=>{
return({isModalVisible:false})
});
}).catch(reason=>{
message.warning('表单输入不允许为空,请检查');
})
}
//弹出框取消的回调
handleCancel=(e)=>{
this.formRef.current.resetFields();
this.setState(()=>{
return({isModalVisible:false})
});
}
render() {
const dataSource = [
{
key: '1',
categoryName: '手机',
},
{
key: '2',
categoryName: '电脑',
},
{
key: '3',
categoryName: '汽车',
},
{
key: '4',
categoryName: '火车',
},
{
key: '5',
categoryName: '飞机',
},
{
key: '6',
categoryName: '地铁',
},
];
const columns = [
{
title: '分类名',
dataIndex: 'categoryName',
key: 'categoryName',
},
{
title: '操作',
render:(item)=>{
return(
<Button type="link" onClick={()=>this.showUpdate(item)}>修改分类</Button>
)
}
},
];
const {operType,isModalVisible}=this.state;
return (
<div>
<Card extra={<Button type='primary' onClick={this.showAdd}>添加</Button>} >
<Table
dataSource={dataSource}
columns={columns}
bordered
pagination={{pageSize:5,showQuickJumper:true}}
/>
</Card>
<Modal
title={operType === 'add'?'新增分类':'修改分类'}
visible={isModalVisible}
onOk={this.handleOk}
okText="确定"
onCancel={this.handleCancel}
cancelText="取消"
forceRender={true}
>
<Form
name="normal_category"
ref={this.formRef}
>
<Form.Item
name="categoryName"
rules={[
{required: true,message: '分类名称不允许为空'},
]}
>
<Input placeholder="请输入分类名称" />
</Form.Item>
</Form>
</Modal>
</div>
)
}
}