react框架如何打印
打印当前页面内容
在React中打印当前页面内容可以使用浏览器内置的window.print()方法。这种方法会触发浏览器的打印对话框,用户可以选择打印机或保存为PDF。
const handlePrint = () => {
window.print();
};
// 在组件中使用
<button onClick={handlePrint}>打印页面</button>
打印特定区域内容
如果需要打印页面中的特定部分而非整个页面,可以创建一个专门的打印样式表隐藏不需要打印的元素。
@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
}
<div className="no-print">这部分不会打印</div>
<div className="print-area">这部分会打印</div>
<button onClick={window.print}>打印选定区域</button>
使用React-To-Print库
react-to-print是一个专门为React设计的打印解决方案库,可以更灵活地控制打印内容。
安装依赖:
npm install react-to-print
使用示例:
import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';
const ComponentToPrint = React.forwardRef((props, ref) => {
return <div ref={ref}>这是要打印的内容</div>;
});
function App() {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<ComponentToPrint ref={componentRef} />
<button onClick={handlePrint}>打印</button>
</div>
);
}
自定义打印样式
通过CSS媒体查询可以专门为打印页面设置样式,确保打印效果符合需求。
@media print {
body {
font-size: 12pt;
color: #000;
}
a::after {
content: " (" attr(href) ")";
}
img {
max-width: 100%;
}
}
打印前预处理数据
有时需要在打印前对数据进行格式化处理,可以在调用打印方法前执行这些操作。
const handlePrint = () => {
// 预处理数据
formatPrintData();
// 延迟确保DOM更新
setTimeout(() => {
window.print();
}, 100);
};






