首页 > 解决方案 > 在 React 中拖放图像

问题描述

我正在尝试使用 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);

这是代码沙盒上的示例。

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

知道怎么做吗?

标签: javascriptreactjsreact-dropzone

解决方案


是的,这不起作用,因为这不是 react-dropzone 的设计目的。引自网站,

简单的 React 钩子为文件创建一个符合 HTML5 的拖放区。

请改用 react-dnd 或 react-beautiful-dnd。


推荐阅读