reactjs - 如何在使用 React 和 styled components 列印時隱藏按鈕?
我想在點擊列印按鈕時隱藏列印按鈕。基本上,一旦開始列印,就隱藏網頁上的列印按鈕。
以下是我的程式碼,
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 和媒體列印來做到這一點。
有人可以幫我處理這個嗎?謝謝。
答案#1
你有各種解決方案:
條件渲染
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'}
`;
使用 Ref
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>
沒有「推薦的方法」,選擇適合你的方式,這取決於情況。
答案#2
你可以使用 CSS 媒體查詢來解決 @media print 的問題,例如如果你的按鈕類名是 print_btn,那麼你可以設置
@media print{
.print_btn{
display:none;
}
}
