问题描述
尝试实现 Dropzone
组件,但运气不佳。我在这里遗漏了什么吗?
import { useState } from 'react';
import { useDropzone } from 'react-dropzone';
import styled from 'styled-components';
export const FilDataForm = (props) => {
const [files,setFiles] = useState([])
const getColor = (props) => {
if (props.isDragAccept) return '#00e676';
if (props.isDragReject) return '#ff1744';
if (props.isDragActive) return '#2196f3';
return '#eeeeee';
}
const onDrop = (file) => {
console.log('HERE!!!!!')
let nf = files;
nf.push(file)
setFiles(nf)
}
const Container = styled.div`
flex:1;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
border-width: 2px;
border-radius: 2px;
border-color: ${props => getColor(props)};
border-style: dashed;
background-color: #fafafa;
color: #bdbdbd;
outline: none;
transition: border .24s ease-in-out;
`
const { getRootProps,getInputProps,isDragActive,isDragAccept,isDragReject } = useDropzone(onDrop);
return (
<div className="modal">
<div className="dialog" style={{ width: "25%",marginBottom: "50px" }}>
<div className="header"><h2>File Uploader</h2></div>
<div className="content">
<Container {...getRootProps({ isDragActive,isDragReject })}>
<input {...getInputProps()} />
<p>Drag 'n' drop some files here,or click to select files</p>
</Container>
<div className="grid-container" style={{ marginTop: "20px",height: "250px" }}></div>
</div>
</div>
</div>
)
}
将文件拖入拖放区域会导致浏览器启动一个新选项卡以尝试打开文件。任何帮助表示赞赏。
编辑 在 Dropzone 中单击也不会打开文件对话框。
解决方法
您需要阻止默认事件。
我正在使用基于类组件的 React Dropzone,这就是我停止默认事件的方式。
{...getRootProps({
className: 'dropzone',onDrop: (event) => event.preventDefault(),})}
完整代码
<Dropzone onDrop={ (files) => fileHandling(files) } >
{({ getRootProps,getInputProps }) => (
<div
{...getRootProps({
className: 'dropzone',})}
style={{ border: '1px solid #707070' }}
>
<input {...getInputProps()} />
<h3 style={{ cursor: 'pointer' }}>
Drag & Drop file or click here to Upload
</h3>
</div>
)}
</Dropzone>
希望能帮到你