# 安装依赖
npm install --save react-to-print
1
# 使用
page-break-before
属性的运用:某些元素设置了 page-break-before: always;
会另起一页。
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
import { ComponentToPrint } from './ComponentToPrint';
const Example = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
return (
<div>
<button onClick={handlePrint}>Print this out!</button>
<div ref={componentRef} >
{ new Array(10).fill(1).map((item,index)=>(
<div key={index} style={{pageBreakBefore: 'always'}}>
{index}
</div>
))}
</div>
</div>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23