You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改React代码实现仅打印表格内容,隐藏其他元素

解决方案

无需新开标签页,通过CSS打印媒体查询即可实现仅打印表格内容、隐藏多余元素的需求,以下是修改后的完整代码:

import * as React from "react";
import { useState, useEffect } from "react";
import Button from "@mui/material/Button";
import axios from "axios";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { jsPDF } from "jspdf";
import "jspdf-autotable";

const ButtonUsage = () => {
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [showTable, setShowTable] = useState(false);
  const recordsPerPage = 10;
  const pagesToShow = 5;

  useEffect(() => {
    if (showTable) {
      getProductData();
    }
  }, [showTable]);

  const getProductData = () => {
    axios.get("https://jsonplaceholder.typicode.com/todos").then((res) => {
      setData(res.data);
    });
  };

  const maxPages =
    data && data.length > 0 ? Math.ceil(data.length / recordsPerPage) : 1;

  const paginate = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  const downloadAsPDF = () => {
    const doc = new jsPDF();

    doc.autoTable({
      head: [["userId", "id", "title", "completed"]],
      body: data
        .slice((currentPage - 1) * recordsPerPage, currentPage * recordsPerPage)
        .map((row) => [
          row.userId,
          row.id,
          row.title,
          row.completed ? "Yes" : "No",
        ]),
    });

    doc.save("table.pdf");
  };

  const printTable = () => {
    window.print();
  };

  return (
    <React.Fragment>
      {/* 打印专用样式 */}
      <style>
        {`
          @media print {
            /* 隐藏Get Data按钮 */
            .MuiButton-root:first-of-type {
              display: none !important;
            }
            /* 隐藏分页栏及内部按钮 */
            .pagination {
              display: none !important;
            }
            /* 移除浏览器默认页眉页脚(含日期、网址等) */
            @page {
              margin: 0;
            }
            /* 设置打印页面边距,避免内容紧贴纸张边缘 */
            body {
              margin: 1.5cm;
            }
            /* 确保表格容器打印时不被页面拆分,且占满宽度 */
            .MuiTableContainer-root {
              break-inside: avoid;
              width: 100% !important;
            }
          }
        `}
      </style>

      <Button variant="contained" onClick={() => setShowTable(true)}>
        Get Data
      </Button>

      {showTable && data && data.length > 0 && (
        <div>
          <TableContainer component={Paper}>
            <Table
              sx={{ minWidth: 650 }}
              size="small"
              aria-label="a dense table"
            >
              <TableHead>
                <TableRow>
                  <TableCell>userId</TableCell>
                  <TableCell>id</TableCell>
                  <TableCell>title</TableCell>
                  <TableCell>completed</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {data
                  .slice(
                    (currentPage - 1) * recordsPerPage,
                    currentPage * recordsPerPage
                  )
                  .map((row) => (
                    <TableRow
                      key={row.id}
                      sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                    >
                      <TableCell component="th" scope="row">
                        {row.userId}
                      </TableCell>
                      <TableCell>{row.id}</TableCell>
                      <TableCell>{row.title}</TableCell>
                      <TableCell>{row.completed ? "Yes" : "No"}</TableCell>
                    </TableRow>
                  ))}
              </TableBody>
            </Table>
          </TableContainer>
          <div className="pagination">
            <button onClick={() => paginate(1)} disabled={currentPage === 1}>
              First
            </button>
            <button
              onClick={() => paginate(currentPage - 1)}
              disabled={currentPage === 1}
            >
              Previous
            </button>
            {Array.from({ length: Math.min(pagesToShow, maxPages) }, (_, i) => (
              <button
                key={i + 1}
                onClick={() => paginate(i + 1)}
                className={currentPage === i + 1 ? "active" : ""}
              >
                {i + 1}
              </button>
            ))}
            <button
              onClick={() => paginate(currentPage + 1)}
              disabled={currentPage === maxPages}
            >
              Next
            </button>
            <button
              onClick={() => paginate(maxPages)}
              disabled={currentPage === maxPages}
            >
              Last
            </button>
            <button onClick={downloadAsPDF}>Download</button>
            <button onClick={printTable}>Print</button>
          </div>
        </div>
      )}
    </React.Fragment>
  );
};

export default ButtonUsage;

核心修改说明

  1. 添加打印媒体查询样式:通过@media print规则,在打印时隐藏Get Data按钮和分页栏,同时移除浏览器默认的页眉页脚(包含日期、网址等元素)。
  2. 优化打印布局:设置打印页面边距,确保表格内容不会紧贴纸张边缘;同时配置表格容器不被页面拆分,保证表格完整性。
  3. 修正原代码小问题:调整表格单元格重复显示userId的错误,改为正确显示id字段。

内容的提问来源于stack exchange,提问作者sandi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:44:53