javascript - 如何使用样式化的组件来设置组件的打印样式?
问题描述
我试图在使用样式组件打印组件时控制大小/方向。我的问题是:如何使用@page CSS at-rule 或其他方法来设置打印组件的样式,以及样式化的组件?
CSS @page 文档:
https://developer.mozilla.org/en-US/docs/Web/CSS/@page
我努力了:
const PrintSchedulesContainer = styled.div`
display: none;
@media print and (min-width: 480px) {
padding: none;
margin: none;
}
`;
和:
const PrintSchedulesContainer = styled.div`
display: none;
@page {
size: landscape;
}
`;
解决方案
您不能针对单个组件进行打印。
您需要隐藏其他元素才能使您的组件成为唯一打印的组件。
@page仅适用于更改打印规则。
@media print允许您定义其他类样式,就像@media screen 一样。
您可以在包装样式的组件中使用@media print,使其全屏显示,并固定为白色背景。
例子:
const PrintableBodyWrapper = styled.div`
@media print {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
}
`;
function App() {
return (
<div className="App">
<PrintableBodyWrapper>
<div style={{ width: 100, height: 100, background: "grey" }}>
I will be printed
</div>
</PrintableBodyWrapper>
</div>
);
}
要更改打印规则,您需要将 @page 添加到全局样式中并呈现全局样式组件。
import styled, { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
@page {
size: landscape;
margin: 5cm;
`;
const PrintableBodyWrapper = styled.div`
@media print {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: black;
display: flex;
justify-content: center;
align-items: center;
}
`;
function App() {
return (
<div className="App">
<GlobalStyle />
<PrintableBodyWrapper>
<div style={{ width: 100, height: 100, background: "grey" }}>
I will be printed
</div>
</PrintableBodyWrapper>
</div>
);
}
推荐阅读
- javascript - 有没有办法在浏览器中使用跨域字体构建 svg?
- java - 如何解决无法驱动../selenium-server-standalone-3.141.59.jar 的模块描述
- flask - 在应用程序中访问\读取 Flask 环境变量
- kubernetes - Istio 允许外部流量在没有 ServiceEntry 的情况下通过?
- python - VSCode 在 linter 中无法解析导入“sys”
- bash - Sed-替换紧接在特定模式之后的下一个字符串单词,但仅在文件中第一次出现
- c# - System.Random 的多个实例是否仍然在 .Net Core 中使用相同的种子?
- git - 重命名master但保留分支历史
- histogram - influxdb 通量中的非累积直方图函数
- pyspark - PySpark 添加 ID 列和过滤器损坏