如何使用react dropzone上传器和react bootstrap Button

350 阅读1分钟

我想在我的 react js 项目中使用react-dropzone-uploader 和自定义输入。当我使用示例文档中的代码时,它工作得很好。但如果我试图将组件从label 改为Button ,当我点击按钮时,它不显示文件浏览器,尽管在页面和开发工具中没有错误。

以下是我的代码

App.js

import "./styles.css";
import DzInput from "./DzInput";

export default function App() {
  return (
    <div className="App">
      <h1>Hello Dropzone</h1>
      <h2>Start editing to see some magic happen!</h2>
      <DzInput />
    </div>
  );
}

DzInput.js

import { getDroppedOrSelectedFiles } from "html5-file-selector";
import Dropzone from "react-dropzone-uploader";
import { Button } from "react-bootstrap";

const DzInput = () => {
  const Input = ({ accept, onFiles, files, getFilesFromEvent }) => {
    const text = files.length > 0 ? "Add more files" : "Choose files";

    return (
      <label // if I change this into <Button then it doesn't work anymore
        variant="primary"
        style={{
          backgroundColor: "#007bff",
          color: "#fff",
          cursor: "pointer",
          padding: 15,
          borderRadius: 3
        }}
      >
        {text}
        <input
          style={{ display: "none" }}
          type="file"
          accept={accept}
          multiple
          onChange={(e) => {
            getFilesFromEvent(e).then((chosenFiles) => {
              onFiles(chosenFiles);
            });
          }}
        />
      </label>
    );
  };

  const CustomInput = () => {
    const handleSubmit = (files, allFiles) => {
      console.log(
        "handlesubmit",
        files.map((f) => f.meta)
      );
      allFiles.forEach((f) => f.remove());
    };

    const getFilesFromEvent = (e) => {
      console.log("getfilesfromevent");
      return new Promise((resolve) => {
        getDroppedOrSelectedFiles(e).then((chosenFiles) => {
          resolve(chosenFiles.map((f) => f.fileObject));
        });
      });
    };

    return (
      <Dropzone
        accept="image/*,audio/*,video/*,.pdf"
        getUploadParams={() => ({ url: "https://httpbin.org/post" })}
        onSubmit={handleSubmit}
        InputComponent={Input}
        getFilesFromEvent={getFilesFromEvent}
      />
    );
  };

  return <CustomInput />;
};

export default DzInput;