首页 > 解决方案 > 反应如何为不同的组件打印横向/纵向

问题描述

我们的 React 应用程序有大约 10 条不同的路线,我们希望它们都可以打印。我们正在使用 css 打印媒体查询来清理样式以进行打印,并且前端有一个单击时调用的按钮window.print()

在 10 条路线中,有 7 个页面看起来更好,landscape而其他 3 个页面更好portrait。目前,@page仅在应用程序的顶级App.scss文件中设置一次。

应用程序.scss

@page {
  size: portrait;
}

@media print and (orientation: portrait) {
  .table-cols {
      max-width: 50%;
  }

  .my-selects { display: none; }
  .my-print-button { display: none; }
  .my-footer { display: none; }
  ...
}

根据路线,如何(如果有的话)@page { size: portrait }切换到景观某些路线?也许可以制作一个landscape类和一个portrait类,每个类都设置自己的@page值,然后这些类将用于路由返回的元素?

标签: cssreactjsprinting

解决方案


function setPageSize(cssPageSize) {
    const style = document.createElement('style');
    style.innerHTML = `@page {size: ${cssPageSize}}`;
    style.id = 'page-orientation';
    document.head.appendChild(style);
}

function PrintIcon({ teamId, orientation = 'portrait' }) {
    // Set orientation of page being printed
    useEffect(() => {
        setPageSize(orientation);
        return () => {
            const child = document.getElementById('page-orientation');
            child.parentNode.removeChild(child);
        };
    }, [orientation]);

    return (
        <div className='print-button' onClick={() => window.print()}>
            Click to Print
        </div>
    );
}

export default PrintIcon;

useEffect调用setPageSize()手动添加@page到头部的函数,它的清理函数删除@page...


推荐阅读