補充
編輯的時候要把 id 賦值為list最后一項的id
否則在編輯的時候新添加一條id會重復
官網(wǎng)例子是單個的
關鍵點改造
remove = index => {
const { form } = this.props;
// 可以使用數(shù)據(jù)綁定來獲取
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;
// 可以使用數(shù)據(jù)綁定來獲取
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('獲取數(shù)組值', 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={'數(shù)量'} required={false}>
{getFieldDecorator(`deviceInventory[${index}].deviceNum`, {
initialValue: k.deviceNum,
rules: [
{
required: true,
message: '請輸入數(shù)量',
},
{
max: 9,
message: '輸入超過限制',
},
],
})(
<Input placeholder="請輸入數(shù)量" 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>
</>
));