[英]Drag and drop area with react-dnd
I'm trying to create a drag and drop area for uploading a single picture and I want to pass it to the application state in the base64 encoded URL using a function onDrop
.我正在尝试创建一个用于上传单张图片的拖放区域,我想使用
onDrop
函数将其传递给 base64 编码 URL 中的应用程序状态。
import React from "react";
import {useDrop} from 'react-dnd'
export default function MyDropTarget(props) {
const [drop] = useDrop({
accept: "box",
collect: (monitor) => {
const res = monitor.getItem();
if (res && res.files) {
const reader = new FileReader();
reader.onloadend = () => props.onDrop(reader.result);
reader.readAsDataURL(res.files[0]);
}
},
});
return (
<div ref={drop}>
Drag item here
</div>);
};
That's how I use this component:这就是我使用这个组件的方式:
<DndProvider backend={HTML5Backend}>
<MyDropTarget style={{height: "100px", width: "100px"}} onDrop={updateImage}/>
</DndProvider>
Since I am new to react-dnd
I am having some problems.由于我是
react-dnd
新手,所以我遇到了一些问题。 I got such an error TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
我收到这样的错误
TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
I think I do not understand the structure of monitor.getItem()
correctly and will be grateful for any hint how to fix it.我想我没有正确理解
monitor.getItem()
的结构,对于如何修复它的任何提示,我将不胜感激。
My guess is that you need to make sure res.files[0]
has a value (not undefined
or null
).我的猜测是你需要确保
res.files[0]
有一个值(不是undefined
或null
)。
if(res.files[0]){
reader.readAsDataURL(res.files[0]);
}
You may also try to check the type of res.files[0]
is if that doesn't help.如果没有帮助,您也可以尝试检查
res.files[0]
的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.