前端好用的函数小工具(亲测好用)
1. html2canvas工具下载前端页面,保存成pdf文件
import React, { useRef } from 'react';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default function index() {
const printRef = useRef(null);
const handlePdfExport = () => {
const print = printRef.current;
const w = print.offsetWidth;
const h = print.offsetHeight;
const body = document.body;
const html = document.documentElement;
const pdf = new jsPDF('p', 'mm', [w, h]);
const offsetTop = print.offsetTop;
const offsetLeft = print.offsetLeft;
const canvas = document.createElement('canvas');
let abs = 0;
const win_i = document.body.clientWidth;
const win_o = window.innerWidth;
if (win_o > win_i) {
abs = (win_o - win_i) / 2;
}
canvas.width = w * 2;
canvas.height = h * 2;
const context = canvas.getContext('2d');
context.scale(2, 2);
context.translate(-offsetLeft - abs, -offsetTop);
html2canvas(print, {
allowTaint: true,
scale: 2,
}).then(function (canvas) {
const contentWidth = canvas.width;
const contentHeight = canvas.height;
const pageHeight = (contentWidth / 592.28) * 841.89;
let leftHeight = contentHeight;
let position = 0;
const imgWidth = 595.28;
const imgHeight = (592.28 / contentWidth) * contentHeight;
const pageData = canvas.toDataURL('image/jpeg', 1.0);
const str = '';
const pdf = new jsPDF(str, 'pt', 'a4');
const title = '资产直接调配单';
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
} else {
while (leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
if (leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save(`${title}.pdf`);
});
};
return(
<div className={styles.mainContainer} ref={printRef}>
...
</div>
)
}
2. 获取当前日期函数
function getNowFormatDate() {
let date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
strDate = date.getDate();
if (month < 10) month = `0${month}`;
if (strDate < 10) strDate = `0${strDate}`;
const dateString = `${year}-${month}-${strDate}`;
return dateString;
}
3. 给antd表格的日期排序
import moment from 'moment';
const columns = [
{
title: '申请日期',
dataIndex: 'applyDate',
sorter: true,
align: 'center',
sorter: (a, b) => {
return new Date(a.parentPlanApprovalDate) >
new Date(b.parentPlanApprovalDate)
? 1
: -1;
},
customRender: function (text) {
if (text == '' || text == null) {
return '/';
} else {
return moment(text).format('YYYY-MM-DD');
}
},
}
]
4. 超过n个字符 / 字段,后边的字用…代替
(1)echarts图表中,以x轴为例
const xAxisLabel = {
show: true,
rotate: 15,
formatter: function (value) {
return value.length > 4 ? value.substring(0, 4) + '...' : value;
},
};
xAxis: {
type: 'category',
axisTick: {
show: false,
},
offset: 10,
axisLabel: {
fontSize: 25,
lineHeight: 80,
margin: 10,
...xAxisLabel,
},
data: data,
}
(2)规定显示n个字段,超过就…显示
const stringName = "香蕉,苹果,橘子,桃子,栗子,梨子,李子";
stringName.split(',').map((item,index)=>{
if (index < 4) {
return item;
}
})
stringName.split(',').length > 4 ? '...' : ' ';