需求
- 点击按钮添加一行中 在table生成一行(可设置默认值) form+table
- 删除和新增放在外部使用
- 可修改
需要下载
yarn add antd
可以参考 ant.design/components/…
主要代码
因为我的添加一行是在外部 我给add()绑定到外部了
注意
Form.List回调返回的field并不是当前项 以及columns render也拿不到当前项(可以尝试打印,一直是一个默认值,具体原因不是很清楚.....)
clum 渲染当前行值需要
name={[field.name, 'key']} fieldKey={[field.fieldKey, 'key']}
tableForm 是Form.List 定义的name 可以理解为form.item中的name
如果想要获取当前行 需要用到
const record = (form.getFieldsValue().tableForm || [])?.[index] || {};
修改赋值行 需要用到
const dataSource = form.getFieldsValue().tableForm; //获取当前form dataSource
dataSource[index].value='我想要修改'
form.setFieldsValue({tableForm: [...dataSource] });
完美解决了只是设置初始值而无法做校验的问题
后续会将整体demo链接挂出来
原文链接:blog.csdn.net/qq_41887214… (这位大哥写的很不错)
测试demo:github.com/Julycc41/ta…
<Form
className="news-table-form"
form={form}
onFinish={onFinish}
initialValues={{
tableForm: dataSource
}}
>
<Form.List name="tableForm">
{(fields, { add, remove }) => {
//remove 自带删除 后续需要用可再加
createRef.current = add; //绑定到ref上,外部进行调用add()
return (
<Table
pagination={false}
expandable={{ defaultExpandAllRows: true, indentSize: 50 }}
className="news-table"
dataSource={fields}
scroll={{ y: 'calc(100vh - 200px)' }}
columns={columns}
loading={loading}
rowKey={(record, index) => {
return record.key;
}}
/>
);
}}
</Form.List>
</Form>
const columns = [
{
title: '图片',
dataIndex: 'cpicUrl',
align: 'center',
render(text, field, index) {
return (
<Form.Item
name={[field.name, 'cpicUrl']}
fieldKey={[field.fieldKey, 'cpicUrl']}
rules={[{ required: true, message: '请上传图片' }]}
getValueFromEvent={(e) => {
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
}}
>
<Upload
name="avatar"
accept=".png,.jpg"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
beforeUpload={(e) => beforeUpload(e, null, null, 1)} //图片校验
customRequest={(e) => customRequest(index, e)} //上传图片
>
<img
style={{ width: '100px', height: '100px' }}
size={64}
icon={<UserOutlined />}
src={form.getFieldsValue().tableForm[index].cpicUrl}
/>
</Upload>
</Form.Item>
);
}
},
{
title: '标题',
width: 200,
dataIndex: 'cTitle',
align: 'center',
render(text, field) {
return (
<Form.Item rules={[{ required: true, message: '请输入标题' }]} name={[field.name, 'cTitle']} fieldKey={[field.fieldKey, 'cTitle']}>
<TextArea maxLength={30} placeholder="不超过30字" />
</Form.Item>
);
}
},
];
新增
createRef.current()//调用
//新增代码块
const dataSource = form.getFieldsValue().tableForm;//获取当前form数据
const dataNew = [
...dataSource,
{
cpicUrl: '',
cSubTitle: '',
cTitle: '',
}
];
form.setFieldsValue({
tableForm: [...dataNew]
});