Koa商城项目-公共组件封装

admin2024-08-23  12

 项目地址

koa_system: 🔥🔥🔥Koa2 + React商城项目前端-React + Antd前端-Vue2 + Element-plus后端-Koa2 + Sequelizehttps://gitee.com/ah-ah-bao/koa_system

上传组件

import React from 'react';
import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { API_URL, getToken } from '../../utils/common';
import type { UploadProps } from 'antd';
import type { UploadPropsType } from './index.type';

const UploadComponent: React.FC<UploadPropsType> = ({
    maxCount = 1,
    showUploadList = true,
    uploadUrl = '/upload',
    typename = 'file',
    onUploadSuccess, 
}) => {
    const props: UploadProps = {
        name:typename,
        action: API_URL + uploadUrl,
        headers: {
            Authorization: getToken() || 'defaultTokenValue',
        },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            switch (info.file.status) {
                case 'done':
                    message.success(`${info.file.name} file uploaded successfully`);
                    if (onUploadSuccess && info.file.response && info.file.response.data && info.file.response.data.url) {
                        onUploadSuccess(info.file.response.data.url); // 调用回调函数
                    }
                    if (onUploadSuccess && info.file.response && info.file.response.data && info.file.response.data.image) {
                        onUploadSuccess(info.file.response.data.image); // 调用回调函数
                    }
                    break;
                case 'error':
                    message.error(`${info.file.name} file upload failed.`);
                    break;
                default:
                    break;
            }
        },
    };

    return (
        <Upload {...props} maxCount={maxCount} showUploadList={showUploadList}>
            <Button icon={<UploadOutlined />}>上传</Button>
        </Upload>
    );
};

export default UploadComponent;

类型校验

export interface UploadPropsType {
    maxCount?:number;
    showUploadList?:boolean;
    uploadUrl?:string;
    typename?:string;
    onUploadSuccess?: (url: string) => void; // 添加回调函数属性
}

使用方式

import { UploadComponent } from "./UploadComponent";

<UploadComponent
  maxCount={1}
  showUploadList={false}
  uploadUrl="/goods/upload"
  typename="file"
  onUploadSuccess={handleUploadSuccess} // 传递回调函数
/>;

// maxCount: 最大上传数量
// showUploadList: 是否显示上传列表
// uploadUrl: 上传地址
// typename: 上传文件类型
// onUploadSuccess: 上传成功回调函数  =>>使用方式
const handleUploadSuccess = (url: string) => {
  setGoodsimg(url); //设置这个返回的路径
};

页面效果

Koa商城项目-公共组件封装,第1张

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!