补充
编辑的时候要把 id 赋值为list最后一项的id
否则在编辑的时候新添加一条id会重复
官网例子是单个的
关键点改造
remove = index => {
const { form } = this.props;
// 可以使用数据绑定来获取
const keys = form.getFieldValue('keys');
const deviceInventory = form.getFieldValue('deviceInventory');
// 至少有一条
if (keys.length === 1) {
return;
}
form.setFieldsValue({
keys: keys.filter((item, key) => key !== index),
deviceInventory: deviceInventory.filter((item, key) => key !== index),
});
};
add = () => {
const { form } = this.props;
// 可以使用数据绑定来获取
const keys = form.getFieldValue('keys');
console.log(id, '添加一条', keys);
id++;
const nextKeys = keys.concat({
id,
});
console.log(id, '完成', nextKeys);
form.setFieldsValue(
{
keys: nextKeys,
},
() => {
console.log('获取数组值', form.getFieldValue('deviceInventory'));
}
);
};
提交
deviceInventory list没有id
keys 只有id
合并后编辑就不会有问题了
let deviceInventory = [];
deviceInventory = fieldsValue.keys.reduce((total, item, index, arr) => {
total.push({
...item,
...fieldsValue.deviceInventory[index],
});
return total;
}, []);
表单
getFieldDecorator('keys', {
initialValue: this.state.form.deviceInventory,
});
const keys = getFieldValue('keys');
const formItems = keys.map((k, index) => (
<>
<Row gutter={24} key={k.id}>
<Col span={7}>
<Form.Item label={'名称'} required={false}>
{getFieldDecorator(`deviceInventory[${index}].deviceName`, {
initialValue: k.deviceName,
rules: [
{
required: true,
message: '请输入名称',
},
{
max: 15,
message: '输入超过限制',
},
],
})(<Input placeholder="请输入名称" disabled={this.state.isDisabled} />)}
</Form.Item>
</Col>
<Col span={7}>
<Form.Item label={'数量'} required={false}>
{getFieldDecorator(`deviceInventory[${index}].deviceNum`, {
initialValue: k.deviceNum,
rules: [
{
required: true,
message: '请输入数量',
},
{
max: 9,
message: '输入超过限制',
},
],
})(
<Input placeholder="请输入数量" disabled={this.state.isDisabled} />
)}
</Form.Item>
</Col>
{keys.length > 1 ? (
<Col span={3}>
<Form.Item>
<Icon
className="dynamic-delete-button"
type="minus-circle-o"
onClick={() => this.remove(index)}
/>
</Form.Item>
</Col>
) : null}
</Row>
</>
));