反应onDrop不仅触发onDragOver和onDragLeave

时间:2019-12-28 19:11:50

标签: reactjs typescript drag-and-drop

我正在尝试使用React实现文件的拖放。我已经从教程中获得了它,当单击dropzone并添加文件时,它工作正常。将文件拖到拖放区上时不起作用。

我添加了一些console.logs来查看执行了什么代码。似乎只有onDragOver和onDragLeave似乎触发了。 onDrop函数永远不会触发。

我也使用react-dropzone库进行切换,但这得到了完全相同的结果:onDrop没有触发。

我已经对最新版本的Google Chrome和FireFox进行了测试,但都无法正常工作。

import * as React from 'react'
const cloudIcon = require('../../../../images/cloud-computing.svg');


interface dropZoneProps {
  onFilesAdded: (event: any, array: any) => void
}

interface dropZoneState {
  highlight: boolean
}


export class DropzoneElem extends React.Component<dropZoneProps, dropZoneState> {
  constructor(props: dropZoneProps) {
    super(props);
    this.state = {
      highlight: false
    }
  }

  private fileInputRef = React.createRef<HTMLInputElement>()

  openFileDialog(event: React.MouseEvent<HTMLDivElement>) {
    this.fileInputRef.current.click();
  }

  handleFileInputChange(event: React.ChangeEvent<HTMLInputElement>) {
    const files = event.target.files;
    const array = this.fileListToArray(files);
    this.props.onFilesAdded(event, array)
  }

  fileListToArray(list: FileList) {
    const array = [];
    for (var i = 0; i < list.length; i++) {
      array.push(list.item(i))
    }
    return array;
  }

  onDragOver(event: React.DragEvent<HTMLDivElement>) {
    event.preventDefault();
    console.log('hit-1')
    this.setState({ highlight: true });
  }

  onDragLeave(event: React.DragEvent<HTMLDivElement>) {
    event.preventDefault();
    console.log('hit-2')
    this.setState({ highlight: false });
  }

  handleOnDrop(event: React.DragEvent<HTMLDivElement>) {
    event.preventDefault();
    console.log('hit-3')

    const files = event.dataTransfer.files;
    const array = Array.from(files).map(file => { return file })

    this.props.onFilesAdded(event, array);
    this.setState({ highlight: false });
  }   

  render() {
    const dragClass = this.state.highlight ? 'dropzone highlight' : 'dropzone';

    return (
      <React.Fragment>
        <div className={dragClass} 
             onClick={event => this.openFileDialog(event)}
             style={{ cursor : 'pointer' }}
             onDragOver={event => this.onDragOver(event)}  
             onDragLeave={event => this.onDragLeave(event)}
             onDrop={event => this.handleOnDrop(event)} >
          <img src={cloudIcon} className='dropzone-icon' />
          <input ref={this.fileInputRef}
                 className='file-input'
                 type='file'
                 multiple
                 onChange={event => this.handleFileInputChange(event)}
          />
          <span>Upload Files</span>
        </div>
      </React.Fragment>
    )
  }
}

0 个答案:

没有答案