使用反应放置区预览多个拖放



我正在尝试在我的应用程序上实现 Dropzone,但如果照片作为多重输入拖放,我无法预览照片。如果我一个接一个地添加它们,它可以正常工作,但如果我选择多个,则只会渲染第一个。

这是我的 onDrop 函数

onDropGeneral = (currentGeneralPhoto) => {
let index;
for (index = 0; index < currentGeneralPhoto.length; ++index) {
const file = currentGeneralPhoto[index];
this.setState({
previewGeneralPhotos: this.state.previewGeneralPhotos.concat(file)
});
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
console.log('URL: ', event.target.result);
this.setState({
generalPhotos: this.state.generalPhotos.concat([{ base64: event.target.result }])
});
};
}
}

这是我的渲染方法:

<h2>Dropped files</h2>
{this.state.previewGeneralPhotos.length > 0 ? <div>
<h2>Preview {this.state.previewGeneralPhotos.length} files...</h2>
<div>{this.state.previewGeneralPhotos.map((file) => <img src={file.preview} alt="preview failed" />)}</div>
</div> : null}
<h2> Upload {this.state.generalPhotos.length} Files </h2>

上传计数显示阵列的正确大小,但预览计数仅计算掉落的第一张照片

所以你的问题是setState可能是异步的。您应该在onDropGeneral函数中使用函数回调进行setState,如下所示:

this.setState(({ previewGeneralPhotos }) => ({
previewGeneralPhotos: previewGeneralPhotos.concat(file)
}))

这将确保您不会意外覆盖以前的previewGeneralPhotos值,并且您实际上按预期添加到现有数组中。

其他一些建议:

  • 确保您的img元素具有键。
  • 我会为整个组件使用文件读取器的实例,而不是在每次调用onDropGeneral方法时创建一个新实例。您可以在componentDidMount中为"load"事件附加事件侦听器,并在componentWillUnmount中删除该侦听器。至少,最好在调用reader.readAsDataURL之前附加该事件侦听器。

最新更新