目录 react封装一个简单的upload组件 component / uploadImg / uploadImg.jsx 使用 效果
react封装一个简单的upload组件
component / uploadImg / uploadImg.jsx
import React, { useState } from 'react' ;
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons' ;
import { message, Upload } from 'antd' ;
const getBase64 = ( img, callback ) => { const reader = new FileReader ( ) ; reader. addEventListener ( 'load' , ( ) => callback ( reader. result) ) ; reader. readAsDataURL ( img) ;
} ;
const beforeUpload = ( file ) => { const isJpgOrPng = file. type === 'image/jpeg' || file. type === 'image/png' ; if ( ! isJpgOrPng) { message. error ( '只能上传图片格式为JPG/PNG的文件!' ) ; } const isLt2M = file. size / 1024 / 1024 < 2 ; if ( ! isLt2M) { message. error ( '图片大小不能超过2MB!' ) ; } return isJpgOrPng && isLt2M;
} ;
const UploadImg = ( ) => { const [ loading, setLoading] = useState ( false ) ; const [ imageUrl, setImageUrl] = useState ( ) ; const customUpload = ( info ) => { console. log ( 'customUpload' , info) ; setLoading ( true ) ; getBase64 ( info. file, ( url ) => { console. log ( 'url' , url) ; setLoading ( false ) ; setImageUrl ( url) ; } ) ; } const uploadButton = ( < div> { loading ? < LoadingOutlined / > : < PlusOutlined / > } < divstyle= { { marginTop : 8 , } } > Upload< / div> < / div> ) ; return ( < Uploadname= "avatar" listType= "picture-card" className= "avatar-uploader" showUploadList= { false } customRequest= { customUpload} beforeUpload= { beforeUpload} > { imageUrl ? ( < imgsrc= { imageUrl} alt= "avatar" style= { { width : '100%' , } } / > ) : ( uploadButton) } < / Upload> ) ;
} ;
export default UploadImg;
使用
< UploadImg / >
效果