我想在单击页面中的打印按钮时隐藏打印按钮。一旦打印开始,基本上隐藏网页上的打印按钮。
下面是我的代码,
const printItems = () => {
window.print();
}
function ItemsTable() {
return(
<>
<TableCell>
<span>first</span>
</TableCell>
<PrintCell>
<CircleIconButton
name="print"
onClick={printItems}
>
</PrintCell>
</>
);
}
const TableCell = styled.div`
display: flex;
flex-direction: row;
`;
const PrintCell = styled(TableCell)`
width: 100px;
justify-content: flex-end;
`;
const CircleIconButton = styled(IconButton)`
border-radius: 15px;
background: none;
width: 32px;
height: 32px;
`;
现在我想在用户单击 CircleIconButton 时隐藏 PrintCell。我怎样才能用 css 和媒体打印来做到这一点。有人可以帮我吗?谢谢。
最佳答案
您有多种解决方案:
条件渲染
function ItemsTable() {
const [isPrinting, setIsPrinting] = useState(false);
const printItems = () => {
setIsPrinting(true);
window.print();
};
return (
<>
{!isPrinting && (
<PrintCell>
<CircleIconButton name="print" onClick={printItems} />
</PrintCell>
)}
</>
);
使用 CSS 变量function ItemsTable() {
const [isPrinting, setIsPrinting] = useState(false);
const printItems = () => {
setIsPrinting(true);
window.print();
};
return (
<>
<PrintCell isVisible={isPrinting}>
<CircleIconButton name="print" onClick={printItems} />
</PrintCell>
</>
);
}
// Or any other css prop like `visible`
const PrintCell = styled(TableCell)`
display: ${props => props.isVisible ? 'block' : 'none'}
`;
使用引用function ItemsTable() {
const printRef = useRef();
const printItems = () => {
printRef.current.style.display = 'none';
window.print();
};
return (
<>
<PrintCell ref={printRef}>
<CircleIconButton name="print" onClick={printItems} />
</PrintCell>
</>
);
}
使用媒体查询const Container = styled.div`
@media print {
${PrintCell} {
display: none;
}
}
`;
const PrintCell = styled(TableCell)`
width: 100px;
justify-content: flex-end;
`;
<Container>
<PrintCell>
<CircleIconButton name="print" onClick={printItems} />
</PrintCell>
</Container>
没有“推荐方式”,选择适合自己的方式,视情况而定。
关于reactjs - 使用 react 和 styled 组件打印时如何隐藏按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63068662/