在React中拖放图像

时间:2019-06-17 12:35:46

标签: javascript reactjs react-dropzone

我正在尝试使用带有显示缩略图的React JS和react-dropzone库来实现拖放行为。

代码如下:

import React from "react";
import ReactDOM from "react-dom";
import Dropzone from "react-dropzone";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      dropzone1: [],
      dropzone2: []
    };
  }

  addFilesToDropzone(files, dropzone) {
    let files_with_preview = [];
    files.map(file => {
      file["preview"] = URL.createObjectURL(file);
      files_with_preview.push(file);
    });

    const new_files = [...this.state[dropzone], ...files_with_preview];
    this.setState({ [dropzone]: new_files });
  }

  render() {

    return (
      <div className="App">
        <Dropzone
          onDrop={files => {
            this.addFilesToDropzone(files, "dropzone1");
          }}
        >
          {({ getRootProps, getInputProps }) => (
            <div {...getRootProps()} className="">
              <input {...getInputProps()} />
              <div style={{ height: 100, backgroundColor: "yellow" }}>
                Drop some files here
                {dropzone1.map(file => (
                  <img
                    src={file.preview}
                    alt={file.path}
                    style={{ width: 40, height: 40 }}
                  />
                ))}
              </div>
            </div>
          )}
        </Dropzone>

        <div style={{ display: "flex", flexDirection: "row", marginTop: 25 }}>
          <div style={{ width: "100%" }}>
            DROPZONE 2
            <Dropzone
              onDrop={files => {
                this.addFilesToDropzone(files, "dropzone2");
              }}
            >
              {({ getRootProps, getInputProps }) => (
                <div {...getRootProps()} className="">
                  <input {...getInputProps()} />
                  <div style={{ height: 100, backgroundColor: "yellow" }}>
                    Drop some files here
                    {this.state.dropzone2.map(file => (
                      <img
                        src={file.preview}
                        alt="dsds"
                        style={{ width: 40, height: 40 }}
                      />
                    ))}
                  </div>
                </div>
              )}
            </Dropzone>
          </div>
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Here is the example on codesandbox.

当我从计算机上的文件夹中拖动文件时,一切正常,但是我希望能够将使用dropzone 1生成的缩略图拖动到dropzone2。但这不起作用。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

是的,那是行不通的,因为那不是react-dropzone设计的目的。来自网站的报价,

  

简单的React钩子可为文件创建HTML5兼容的拖放区域。

改为使用react-dnd或react-beautiful-dnd。

答案 1 :(得分:0)

您可以使用另一个软件包:react-file-drop