泛型限定formData类型组件
<DownLoadButton<{date:string}> url="/" formData={{date:""}} />
泛型使用函数
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) => {
useEffect(() => {
console.log(props.formData);
}, [props.url, props.formData]);
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",
responseType: "blob",
},
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,
})
);
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;