泛型下载组件笔记

111 阅读1分钟

泛型限定formData类型组件

<DownLoadButton<{date:string}> url="/" formData={{date:""}} />

泛型使用函数

// 使用Props接入泛型组件传入类型
type Props<T = {}> = {
  className?: string;
  url: string;
  formData?: {
    [P in keyof T]: T[P];
  };
};
function DownLoadButton<T>(fprops: Props<T>) {
  const ButtonLoad = React.forwardRef<DownLoadRef, Props<T>>((props, ref) => { return <div />});
   return <ButtonLoad url={fprops.url} formData={fprops?.formData}></ButtonLoad>;
  }
 

demo如下

import store from "@/redux/store";
import service from "@/utils/axios-helper";
import { DownloadOutlined } from "@ant-design/icons";
import { Button } from "antd";
import React, { useEffect } from "react";

export type DownLoadRef = {};
type Props<T = {}> = {
  className?: string;
  url: string;
  formData?: {
    [P in keyof T]: T[P];
  };
};

function DownLoadButton<T>(fprops: Props<T>) {
  const ButtonLoad = React.forwardRef<DownLoadRef, Props<T>>((props, ref) => {
   
    //TODO:响应
    useEffect(() => {
      console.log(props.formData);
      //debugger;
    }, [props.url, props.formData]);
    // TODO:事件
    const exportALL = () => {
      (fetch as any)(fprops.url, {
        method: "post",
        mode: "cors",
        headers: {
          Accept:
            "application/prs.hal-forms+json, application/hal+json, application/json, */*",
          "Content-Type": "application/json; charset=UTF-8", //"multipart/form-data",
          // "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", //"application/json",
          responseType: "blob", // "arraybuffer", //
         
        },
        body: props?.formData ? JSON.stringify(props.formData) : "",
      }).then(async (da: any) => {
        let fileHeader = new Map<string, string>(
          decodeURIComponent(da.headers.get("content-disposition"))
            .split(";")
            .map((item) => item.split("=")) as []
        );

        let url = URL.createObjectURL(
          new Blob([await da.blob()], {
            type: da.blob.type,
            //type: "application/vnd.ms-excel",
            //"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            //"application/vnd.ms-excel"
          })
        );
        let a = document.createElement("a");
        a.target = "_banck";
        a.href = url;
        a.download = fileHeader.get("filename") || "租户列表下载";
        document.body.appendChild(a);
        a.click();
      });
      return;
    };
 
    return (
      <Button
        type="default"
        className={`${fprops.className} downloadButton`}
        icon={<DownloadOutlined />}
        onClick={exportALL}
      >
        下载
      </Button>
    );
  });

  return <ButtonLoad url={fprops.url} formData={fprops?.formData}></ButtonLoad>;
}
export default DownLoadButton;