Reac利用插件实现选定内容打印功能

536 阅读1分钟

最近在做一个前端随机从题库生成试卷的项目,生成试卷之后需要自定义打印,想起之前需要在知乎打印文章,使用Chrome选中内容之后,打印可以只打印选中内容,考虑到一般用户不会去特意找这些功能,在github上找到这个打印插件使用,附githhub地址

https://github.com/gregnb/react-to-print

以下步骤实现:

1.项目中安装依赖

npm install react-to-print --save-dev

2.引入 react-to-print

import ReactToPrint from 'react-to-print'

3.在项目中使用

 {/* 打印按钮 */}
<ReactToPrint    
   trigger={() => <Button style={{marginLeft: '30px'}} type='dashed' >打印</Button> }    
   content={() => this.componentRef}    
   copyStyles={true} 
/>

{/* 需要打印的模块 */}
<div className='page' ref={el => (this.componentRef = el)}
{/* 自定义打印内容 */}
</div>

4.实际效果预览: