React中使用react-to-print实现动态数据表格打印

1,356 阅读2分钟

参数说明

参数类型描述
bodyClassstring?传递给打印窗口主体的类
contentfunction返回组件参考值的函数。然后将该参考值的内容用于打印
copyStylesboolean?将所有< style>和< link type=“stylesheet” />标签从< head>父窗口内部复制到打印窗口。(默认值:true)
documentTitlestring?设置打印文件的标题
onAfterPrintfunction?打印后触发的回调功能
onBeforeGetContentfunction?在库收集页面内容之前触发的回调函数。返回void或Promise。可用于在打印之前更改页面上的内容
onBeforePrintfunction?打印前触发的回调功能。返回void或Promise。注意:此功能在打印之前立即运行,但在收集页面内容之后才运行。要在打印之前修改内容,请onBeforeGetContent改用
onPrintErrorfunction(errorLocation: ('onBeforePrint','onBeforeGetContent','print'), error: Error)?如果打印错误严重到无法继续打印,将调用的回调函数。目前仅限于onBeforeGetContent或中的Promise拒绝onBeforePrint。使用它尝试再次打印。errorLocation会告诉您Promise在哪个回调中被拒绝
pageStylestring?覆盖默认的打印窗口样式
removeAfterPrintboolean?执行操作后,卸下打印iframe。默认为false
triggerfunction返回React组件或HTML元素的函数

第一步:安装依赖

npm install --save react-to-print

第二步:在页面引入react-to-print

import ReactToPrint from 'react-to-print';

第三步:使用

//设置触发打印的按钮
<ReactToPrint
  trigger={() => (
    <Button className="ml-10">
      打印
    </Button>
  )}
  content={() => this.componentRef}
  //设置打印样式
  pageStye="@page {padding-top:10px}"
  copyStyles={false}
  //这里是第一处设置:打印未显示元素的关键,默认情况copyStyles是为true的,
  //打印未显示的元素时,我们需要把它设置为false,这样打印出来的页面才不会是空白页。
/>

//打印内容
<div style={{ overflow: 'hidden', height: 0 }}>
  {/*headerData是动态表头数据,如:[{id:1, name:'测试列1'}, {id:1, name:'测试列2'}],dataSource是动态表格数据,如:[{1: '数据', 2: '数据2'}, {1: '数据3', 2: '数据4'}]*/}
  <table
    border="1px solid #ccc"
    cellSpacing="0"
    cellPadding="5"
    style={{
      borderCollapse: 'collapse',
      width: '100%',
    }}
  >
    <thead>
      {headerData &&
        headerData.map((v) => {
          return <th key={v.id}>{v.name}</th>;
        })}
    </thead>
    <tbody>
      {dataSource &&
        dataSource.map((item) => (
          <tr style={{ pageBreakInside: 'avoid' }}>
            {/*避免行内容被分页切割*/}
            {headerData &&
              headerData.map((v) => (
                <td style={{ textAlign: 'center' }}>
                  {item[v.id] || item[v.id] === 0 ? item[v.id] : '-'}
                </td>
              ))}
          </tr>
        ))}
    </tbody>
  </table>
</div>

具体使用也可以查看官方文档:github.com/gregnb/reac…