如何使用react-to-print在一页中重复打印指定组件?
实现react-to-print重复输出指定组件到同一打印页的方案
方案1:直接在打印容器中重复渲染组件
如果允许页面显示和打印输出一致的重复组件,直接修改componentRef包裹的内容,循环渲染目标组件即可。比如要重复3次,可通过数组循环生成:
import React, {useRef} from 'react'; import { useReactToPrint } from 'react-to-print'; import MyComponent from './myComponent'; import OtherComponent from './otherComponent'; const CreateAtt = () => { const componentRef = useRef(); const printData = useReactToPrint({ content: () => componentRef.current, documentTitle: 'doc', }); // 定义重复次数 const repeatCount = 3; return ( <> <div className='d-flex justify-content-between'> <div ref={componentRef}> {/* 循环渲染MyComponent */} {Array.from({ length: repeatCount }).map((_, index) => ( <MyComponent key={index} /> ))} </div> <OtherComponent /> </div> <button className='btn btn-primary download-button' onClick={printData}>print</button> </> ) } export default CreateAtt;
方案2:使用隐藏的打印专用容器(页面仅显示一次,打印重复输出)
如果不想在页面上展示重复组件,仅在打印时输出多份,可以单独创建一个隐藏容器专门用于打印,页面保持原有单组件显示:
import React, {useRef} from 'react'; import { useReactToPrint } from 'react-to-print'; import MyComponent from './myComponent'; import OtherComponent from './otherComponent'; const CreateAtt = () => { // 页面显示的组件ref const displayRef = useRef(); // 打印专用的隐藏容器ref const printRef = useRef(); const printData = useReactToPrint({ content: () => printRef.current, documentTitle: 'doc', }); const repeatCount = 3; return ( <> <div className='d-flex justify-content-between'> <div ref={displayRef}> <MyComponent /> </div> <OtherComponent /> </div> {/* 隐藏容器,仅用于打印渲染 */} <div ref={printRef} style={{ display: 'none' }} > {Array.from({ length: repeatCount }).map((_, index) => ( <MyComponent key={index} /> ))} </div> <button className='btn btn-primary download-button' onClick={printData}>print</button> </> ) } export default CreateAtt;
额外注意事项
- 避免组件分页拆分:给
MyComponent添加CSS样式page-break-inside: avoid;,防止单个组件被拆分到不同页面;若要所有重复组件都在同一页,可给打印容器添加page-break-after: avoid;。 - 动态数据处理:如果
MyComponent依赖动态数据,需确保每次渲染的内容符合预期(比如传递对应props或保证数据一致性)。
内容的提问来源于stack exchange,提问作者Houssam Mrabet
相关产品推荐
相关产品推荐

