当前位置:首页 > React

react实现模板打印

2026-01-27 05:00:03React

React 实现模板打印的方法

使用 react-to-print 库

安装 react-to-print 库:

npm install react-to-print

创建一个可打印的组件:

import React, { useRef } from 'react';
import { useReactToPrint } from 'react-to-print';

const PrintableComponent = React.forwardRef((props, ref) => {
  return (
    <div ref={ref}>
      <h1>打印内容标题</h1>
      <p>这是要打印的内容</p>
    </div>
  );
});

const PrintButton = () => {
  const componentRef = useRef();
  const handlePrint = useReactToPrint({
    content: () => componentRef.current,
  });

  return (
    <div>
      <PrintableComponent ref={componentRef} />
      <button onClick={handlePrint}>打印</button>
    </div>
  );
};

使用 window.print() 方法

直接调用浏览器打印功能:

const PrintComponent = () => {
  const printContent = () => {
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>打印页面</title>
          <style>
            @media print {
              body { font-family: Arial; }
              .no-print { display: none; }
            }
          </style>
        </head>
        <body>
          <h1>打印内容</h1>
          <p>这是要打印的正文</p>
        </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.print();
  };

  return <button onClick={printContent}>打印</button>;
};

使用 CSS 控制打印样式

添加打印专用样式:

@media print {
  .no-print {
    display: none;
  }
  .print-only {
    display: block;
  }
  body {
    font-size: 12pt;
    color: #000;
  }
}

在组件中应用:

<div>
  <div className="no-print">屏幕显示但不打印的内容</div>
  <div className="print-only">仅打印时显示的内容</div>
  <button onClick={() => window.print()}>打印</button>
</div>

处理复杂打印布局

对于需要特殊布局的打印内容:

const ComplexPrintLayout = () => {
  const printRef = useRef();

  const handlePrint = () => {
    const content = printRef.current.innerHTML;
    const printWindow = window.open('', '_blank');
    printWindow.document.write(`
      <html>
        <head>
          <title>复杂打印布局</title>
          <style>
            @page {
              size: A4 landscape;
              margin: 1cm;
            }
            table {
              width: 100%;
              border-collapse: collapse;
            }
            th, td {
              border: 1px solid #ddd;
              padding: 8px;
            }
          </style>
        </head>
        <body>
          ${content}
        </body>
      </html>
    `);
    printWindow.document.close();
    printWindow.print();
  };

  return (
    <div>
      <div ref={printRef}>
        <table>
          <thead>
            <tr>
              <th>列1</th>
              <th>列2</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>数据1</td>
              <td>数据2</td>
            </tr>
          </tbody>
        </table>
      </div>
      <button onClick={handlePrint}>打印表格</button>
    </div>
  );
};

打印前数据处理

在打印前处理数据:

react实现模板打印

const DataPrintComponent = () => {
  const [data, setData] = React.useState([]);
  const printRef = useRef();

  const fetchDataBeforePrint = async () => {
    const response = await fetch('api/data');
    const result = await response.json();
    setData(result);
    setTimeout(() => window.print(), 500); // 等待数据渲染
  };

  return (
    <div>
      <div ref={printRef}>
        {data.map(item => (
          <div key={item.id}>{item.name}</div>
        ))}
      </div>
      <button onClick={fetchDataBeforePrint}>加载并打印数据</button>
    </div>
  );
};

这些方法提供了从简单到复杂的打印解决方案,可以根据具体需求选择适合的方式实现React应用的打印功能。

标签: 模板react
分享给朋友:

相关文章

react如何部署

react如何部署

部署 React 应用的常见方法 使用静态服务器部署 React 应用在构建后会生成静态文件,可以直接通过静态服务器部署。常用的静态服务器包括 Nginx、Apache 等。 运行构建命令生成静态文…

react如何查

react如何查

React 查询方法 React 提供了多种查询 DOM 元素的方式,以下是几种常见的方法: 使用 ref 通过 useRef 钩子可以获取 DOM 节点的引用,适用于直接操作 DOM 的场景。…

react如何调试

react如何调试

调试 React 应用的方法 使用 React Developer Tools React Developer Tools 是 Chrome 和 Firefox 的浏览器扩展,可以检查组件树、状态和…

react如何diff

react如何diff

React Diff 算法原理 React 的 Diff 算法是 Virtual DOM 的核心部分,用于高效更新真实 DOM。其核心思想是通过对比新旧 Virtual DOM 树的差异,最小化 DO…

react如何分

react如何分

React 分页实现方法 在 React 中实现分页功能可以通过多种方式完成,以下是几种常见的方法: 使用状态管理分页数据 在组件内部维护当前页码和每页数据量的状态,通过计算切片数据实现分页。…

react 如何获取dom

react 如何获取dom

获取 DOM 的方法 在 React 中,可以通过 useRef 或 createRef 来获取 DOM 节点。useRef 是函数组件中常用的方法,而 createRef 通常用于类组件。 使用…