react封装一个简单的upload组件(待完善)

目录

  • 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 handleChange = (info) => { // 监听文件的上传状态
  //   if (info.file.status === 'uploading') {
  //     setLoading(true);
  //     return;
  //   }
  //   if (info.file.status === 'done') {
  //     // Get this url from response in real world.
  //     getBase64(info.file.originFileObj, (url) => {
  //       setLoading(false);
  //       setImageUrl(url);
  //     });
  //   }
  // };
  // 自定义上传函数
  const customUpload = (info)  => {
    console.log('customUpload',info);
    setLoading(true);
    getBase64(info.file, (url) => { // 把本地图片转换为base64展示
      console.log('url',url);
      setLoading(false);
      setImageUrl(url);
    });
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  return (
    // onChange={handleChange}
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      customRequest={customUpload}
      beforeUpload={beforeUpload}
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};
export default UploadImg;

使用

<UploadImg />

效果

react封装一个简单的upload组件(待完善)_第1张图片

你可能感兴趣的:(react组件,react.js,javascript,前端)