reactjs React onDrop未触发

rvpgvaaj  于 2023-04-05  发布在  React
关注(0)|答案(7)|浏览(162)

下面是我尝试使用的示例代码,即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>)
  }
}
kgsdhlau

kgsdhlau1#

您必须像这样preventDefault()**dragover**事件的行为:

onDragOver = (e) => {
    let event = e as Event;
    event.stopPropagation();
    event.preventDefault();
}

阻止dragover事件中的默认行为“表明元素是可拖动位置”,如MDN文档中所示,herehere。然后drop事件将工作。

0md85ypi

0md85ypi2#

简单地防止默认ondragover事件,然后它的工作。

onDragOver = (event) => {
    event.preventDefault();
}
return (<div onDragOver={this.onDragOver} {...others}>{children}</div>);
6bc51xsx

6bc51xsx3#

您的代码中有一个问题,您必须将事件分配给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>
    )
  }
liwlm1x9

liwlm1x94#

window.ondragover = function(e) { e.preventDefault(); return false };
window.ondrop = function(e) { e.preventDefault(); return false };
goucqfw6

goucqfw65#

浏览器默认情况下会阻止“drop”动作,所以你需要阻止他们这样做!event.preventDefault()会像你提到的那样处理它。

wf82jlnq

wf82jlnq6#

onDrop={files => this.onFileDrop}>

这个,应该变成这样:

onDrop={this.onFileDrop}>

当你使用“this.”来调用函数时,你需要它在构造函数中:

constructor(props) {
    super(props);

    this.onFileDrop = this.onFileDrop.bind(this);
  }

功能:

onFileDrop(event) { 
 event.preventDefault(); 
 console.log("qwerty")
}
jc3wubiy

jc3wubiy7#

你需要调用函数来启动它(使用括号):

render() {
    return (
      <div>
        onDragEnter={this.onDragEnter}
        onDragOver={() => { return false }}
        onDrop={files => this.onFileDrop()}> // you were missing the "()"
        Drag and drop file here
      </div>)
  }

相关问题