我正在使用react-dropzone
,我想在页面加载后立即自动打开文件上传对话框。
我编写了以下代码,但我无法理解如何使其自动打开,这将是我做错了,ref
因为我可以访问它的属性。
你能帮我个忙吗?
链接:codesandbox
import React from "react";
import { useDropzone } from "react-dropzone";
import { Chip } from "@material-ui/core";
import { AttachFile } from "@material-ui/icons";
const Dropzone = React.forwardRef(
({ multiple = false, onOperation, onDelete }, ref) => {
const [myFile, setMyFile] = React.useState([]);
const inputRef = React.useRef(null);
//const inputRef = React.createRef();
React.useImperativeHandle(
ref,
() => ({
upload: () => inputRef.current
}),
[inputRef]
);
const onDrop = React.useCallback(
(acceptedFiles) => {
setMyFile([...acceptedFiles]);
onOperation(acceptedFiles);
},
[myFile, onOperation]
);
const { getRootProps, getInputProps } = useDropzone({
onDrop
});
const removeAll = () => setMyFile([]);
const file = myFile.map((file, key) => (
<Chip
key={key}
icon={<AttachFile />}
label={`${file.path} - ${file.size} bytes`}
color="primary"
onDelete={() => {
removeAll();
onDelete && onDelete();
}}
style={{
cursor: "pointer",
backgroundColor: "#2196f3"
}}
/>
));
const label = "File";
return (
<span {...getRootProps({ className: "drop-zone" })}>
<input ref={inputRef} {...getInputProps()} multiple={multiple} />
{file.length > 0 ? (
file
) : (
<Chip
icon={<AttachFile />}
label={label}
color="primary"
style={{
cursor: "pointer",
backgroundColor: "#2196f3"
}}
/>
)}
</span>
);
}
);
export default function App() {
const onDrop = (file) => console.log(file);
//const ref = React.useRef(null);
const ref = React.createRef();
React.useEffect(() => {
console.log("Ref:", ref.current, ref.current.upload());
/*if (ref.current) {
ref.current.open();
}*/
}, []);
return (
<div className="App">
<Dropzone ref={ref} onOperation={onDrop} />
</div>
);
}