1. 前言
1.1 你能学到
- 拖拽上传的API
-
2. 需求分析
基本的拖动、上传、点击预览
- 更多的配置项
- 可视化
2.1 大致流程
2.2 组件属性
3. code
3.1 上传文件功能
借助表单 form 功能,再设置input type
为 file,来完成文件的选择。然后再用 form 的 submit 来提交。
因为文件是二进制文件,所以要设置encType=’multiline/form-data’JSONPlaceholder: 提供免费的Fake API 服务
<div style={{ marginTop: '100px', marginLeft: '100px' }}>
<form
method='post'
encType='multiline/form-data'
action='http://jsonplaceholder.typicode.com/posts'
>
<input type='file' name='FILE' />
<button type='submit'>Submit</button>
</form>
</div>
3.2 拖拽上传功能
interface DraggerProps {
onFile: (file: FileList) => void
}
export const Dragger: FC<DraggerProps> = (props) => {
const { onFile, children } = props
const [dragOver, setDragOver] = useState(false)
const cnames = classNames('zhou-upload-dragger', {
'is-dragover': dragOver,
})
const handleDrag = (e: DragEvent<HTMLElement>, over: boolean) => {
e.preventDefault()
setDragOver(over)
}
const handleDrop = (e: DragEvent<HTMLElement>) => {
e.preventDefault()
setDragOver(false)
onFile(e.dataTransfer.files)
}
return (
<div
className={cnames}
onDragOver={(e) => handleDrag(e, true)}
onDragLeave={(e) => handleDrag(e, false)}
onDrop={handleDrop}
>
<Icon icon='upload' size='5x' theme='secondary' />
{children}
<p>将文件拖到这里上传</p>
</div>
)
}
export default Dragger
主要用到 onDragOver
、onDragLeave
、onDrop
事件
3.3 可视化
export interface ProgressProps {
percent: number
strokeHeight?: number
showText?: boolean
styles?: CSSProperties
theme?: ThemeProps
}
const Progress: FC<ProgressProps> = (props) => {
const { percent, strokeHeight, showText, styles, theme } = props
return (
<div className='zhou-progress-bar' style={styles}>
<div
className='zhou-progress-bar-outer'
style={{ height: `${strokeHeight}px` }}
>
<div
className={`zhou-progress-bar-inner color-${theme}`}
style={{ width: `${percent}%` }}
>
{showText && (
<span className='inner-text'>{`${percent}%`}</span>
)}
</div>
</div>
</div>
)
}
组要借助模板字符串+CSS