import logo from './logo.svg';
import { Button, Form, Table, Space, Input, Popconfirm, Select } from 'antd';
import React, { useState } from "react";
import './App.css';
function App() {
const [ form ] = Form.useForm();
const [ dataList, setDataList ] = useState([]);
const delRow = (index) => {
const dataListValues = form.getFieldsValue(true).list;
dataListValues.splice(index, 1);
setDataList([...dataListValues]);
}
const addRow = () => {
const dataListValues = form.getFieldsValue(true).list || [];
const newRow = {
certificateLevel: '',
certificateName: '',
certificateType: '',
}
setDataList([
...dataListValues,
newRow
])
form.setFieldsValue({list: [...dataListValues, newRow]})
}
const save = (tip) => {
if(form) {
form.validateFields().then(res => {
let value = form.getFieldsValue(true).list;
console.log(value, "value");
})
}
}
const tableColumns = [
{
key: 'certificateName',
title: <span><span style={{ color: 'red' }}>*</span>证书名称</span>,
dataIndex: 'certificateName',
width: 150,
render: (_, record, index) => (
<Form.Item name={ ["list", index, "certificateName"] } key={ index } initialValue={ _ } rules={[{
"required": true,
"message": "请输入资料名称" },
{
pattern: /^[^\s]*$/,
message: '禁止输入空格',
}]}>
<Input maxLength={ 50 }/>
</Form.Item>
)
},
{
key: 'certificateType',
title: <span><span style={{ color: 'red' }}>*</span>证书类型</span>,
dataIndex: 'certificateType',
width: 150,
render: (_, record, index) => (
<Form.Item name={ ["list", index, "certificateType"] } key={ index } initialValue={ _ } rules={[{
"required": true,
"message": "请选择证书类型" }]}>
<Select getPopupContainer={triggerNode => triggerNode.parentNode}>
<Select.Option value={"1"}>1</Select.Option>
<Select.Option value={"2"}>2</Select.Option>
<Select.Option value={"3"}>3</Select.Option>
</Select>
</Form.Item>
)
},
{
key: 'certificateLevel',
title: '证书等级',
dataIndex: 'certificateLevel',
width: 150,
render: (_, record, index) => (
<Form.Item name={ ["list", index, "certificateLevel"] } key={ index } initialValue={ _ }>
<Input maxLength={ 50 }/>
</Form.Item>
)
},
{
key: 'operation',
title: '操作',
dataIndex: 'operation',
width: 150,
fixed: 'right',
render: (_, record, index) => (
<Space direction="horizontal" size="small">
<Popconfirm
title="确认删除?"
onConfirm={ () => delRow(index) }
okText="确认"
cancelText="取消"
>
<Button type="link">删除</Button>
</Popconfirm>
</Space>
)
}
]
return (
<div className="App">
<Button type="primary" onClick={ addRow }>新增一行</Button>
<Form form={ form }>
<Table rowKey="id" scroll={{ x: 1200 }} dataSource={[...dataList]} pagination={false} columns={tableColumns} />
</Form>
<Button onClick={save}>提交</Button>
</div>
);
}
export default App;
react表格验证
最新推荐文章于 2024-04-18 17:25:59 发布