react实现打印
React 实现打印功能的方法
在 React 中实现打印功能可以通过多种方式完成,以下是几种常见的方法:
使用 window.print() 方法
直接调用浏览器的打印 API 是最简单的方式。创建一个按钮或触发事件,调用 window.print() 即可打开浏览器的打印对话框。
const handlePrint = () => {
window.print();
};
return <button onClick={handlePrint}>打印页面</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}>
<h1>打印内容</h1>
<p>这是需要打印的部分</p>
</div>
);
});
const MyComponent = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<ComponentToPrint ref={componentRef} />
<button onClick={handlePrint}>打印</button>
</div>
);
};
自定义打印样式
通过 CSS 媒体查询可以控制打印时的样式,隐藏不需要打印的元素或调整布局。

@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
}
打印特定区域
如果需要打印页面中的特定区域,可以创建一个隐藏的 iframe,将要打印的内容放入 iframe 中,然后调用 iframe 的打印方法。
const printSpecificArea = (content) => {
const frame = document.createElement('iframe');
frame.style.display = 'none';
document.body.appendChild(frame);
frame.contentDocument.write(content);
frame.contentDocument.close();
frame.contentWindow.focus();
frame.contentWindow.print();
document.body.removeChild(frame);
};
处理打印分页
使用 CSS 的 page-break 属性可以控制打印时的分页效果。
.page-break {
page-break-after: always;
}
以上方法可以根据具体需求选择使用,react-to-print 库提供了最完整的解决方案,适合大多数 React 打印场景。





