typescript React onDrop 没有触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50230048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React onDrop is not firing
提问by Psb
Below is the sample code which I'm trying to use, which is react + TypeScript. onDragEnter and onDragOver are working properly but not the onDropevent.
下面是我尝试使用的示例代码,即 react + TypeScript。onDragEnter 和 onDragOver 工作正常,但没有onDrop事件。
import * as React from 'react';
export class FileZone extends React.Component {
onDragOver = (e) => {
let event = e as Event;
event.stopPropagation();
}
onDragEnter = (e) => {
let event = e as Event;
event.stopPropagation();
}
onFileDrop = (e) => {
let event = e as Event;
event.stopPropagation();
console.log("onFileDrop");
alert("dropped")
}
render() {
return (
<div>
onDragEnter={this.onDragEnter}
onDragOver={this.onDragOver}
onDrop={this.onFileDrop}>
Drag and drop file here
</div>)
}
}
回答by Psb
Finally i got the issue, for some reason i have to handle the onDragOverlike this :
最后我遇到了这个问题,出于某种原因,我必须像这样处理onDragOver:
onDragOver = (e) => {
let event = e as Event;
event.stopPropagation();
event.preventDefault();
}
this solved my issue.
这解决了我的问题。
回答by JamesYin
Simply prevent default ondragover event then it works.
只需阻止默认的 ondragover 事件即可。
onDragOver = (event) => {
event.preventDefault();
}
return (<div onDragOver={this.onDragOver} {...others}>{children}</div>);
回答by Piyush Bhati
There is a problem in your code you have to assign event to div
您的代码存在问题,您必须将事件分配给 div
render() {
return (
<div //you have to remove additional > from here
onDragEnter={this.onDragEnter}
onDragOver={this.onDragOver}
onDrop={this.onFileDrop}>
Drag and drop file here
</div>
)
}
回答by Savandy
onDrop={files => this.onFileDrop}>
This, should become this:
这,应该变成这样:
onDrop={this.onFileDrop}>
And as you are using 'this." to call the function you will need it to be in the constructor:
当您使用“this.”来调用该函数时,您将需要它在构造函数中:
constructor(props) {
super(props);
this.onFileDrop = this.onFileDrop.bind(this);
}
Function:
功能:
onFileDrop(event) {
event.preventDefault();
console.log("qwerty")
}
回答by Rodius
You need to call the function to fire it up (use the parenthesis):
您需要调用函数来启动它(使用括号):
render() {
return (
<div>
onDragEnter={this.onDragEnter}
onDragOver={() => { return false }}
onDrop={files => this.onFileDrop()}> // you were missing the "()"
Drag and drop file here
</div>)
}
回答by Makoto Hirata
window.ondragover = function(e) { e.preventDefault(); return false };
window.ondrop = function(e) { e.preventDefault(); return false };
回答by BaN
The browsers prevent the "drop" actions by default, so you need to prevent them doing that! event.preventDefault() will handle it as you mentioned.
默认情况下,浏览器会阻止“放置”操作,因此您需要阻止它们这样做!event.preventDefault() 将按照您提到的方式处理它。