我具有以下功能,可将<input type="file" multiple />
的附件添加到父母的状态。
在用户要添加另一个附件,新的附件覆盖现有附件之前,该方法工作正常,如何将新附件添加到现有附件数组中?
handleAddAttachments = fileList => {
this.props.handleChange('attachments', Array.from(fileList));
};
我尝试过,但是似乎不起作用。
handleAddAttachments = fileList => {
const { attachments } = this.props.ticket;
this.props.handleChange('attachments', [...attachments, fileList]);
};
父handleChange
函数:
makeHandleChange = (pageName, change) => {
this.setState({
ticket: { ...this.state.ticket, [pageName]: change },
});
};
答案 0 :(得分:1)
在第二个版本中,您缺少Array.from()
部分。从fileInput所做的更改不是直接由数组组成,因此散布运算符不起作用。
这应该可以解决问题:
handleAddAttachments = fileList => {
const { attachments } = this.props.ticket;
this.props.handleChange('attachments', [...attachments, ...Array.from(fileList)]);
};
有关为什么它不是数组的更多信息,您可以在这里找到一些信息:Why isn't the FileList object an array?
感谢@sigmus,我将缺失的价差添加到了Array.from()