【发布时间】:2021-06-04 22:00:40
【问题描述】:
我创建了一个自定义打印函数来打印特定 div 内的内容(我找不到它的 React 库)。
我的自定义函数:
export function printReports(divId){
var content = document.getElementById(divId).innerHTML;
var mywindow = window.open('', 'Print', 'height=600,width=800');
mywindow.document.write('<html><head><title>Print</title>');
mywindow.document.write('</head><body >');
mywindow.document.write(content);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus()
mywindow.print();
mywindow.close();
return true;
}
然后,我有一个基本的收据组件:
import React, { useState, useEffect } from 'react';
import { Table, Button } from 'reactstrap';
import NumberFormat from 'react-number-format';
import moment from 'moment';
import * as customFuncs from '../util/myFunctions';
import * as api from '../api/Tenants';
const DepositReceipt = (props) => {
const tempTransactionID = props.tempTransactionID;
const [ data, setData ] = useState({});
useEffect(() => {
async function fetchData() {
setLoading(true);
setData(await tenantAPI.getTempTransactionDetails(tempTransactionID)); // get data from database
setLoading(false);
}
fetchData();
}, [tempTransactionID])
const totalTransaction = parseFloat(data.HousingAmount) + parseFloat(data.TenantAmount);
return (
<>
<div style={{marginTop: '1%', marginLeft: '1%', marginRight: '1%', marginBottom: '1%'}}>
<Button color="primary" onClick={() => customFuncs.printReports('DepositReceiptDiv')}>Print</Button>
</div>
<div id="DepositReceiptDiv" className="row">
<div className="col-sm-4 offset-md-4">
<p style={{textAlign: 'center'}}>Receipt for Payment</p>
<Table bordered>
<tr>
<th>
<p>
{data.TenantFName} {data.TenantLName} <br />
Unit {data.UnitName} <br />
<NumberFormat value={data.TenantPhone} displayType={'text'} format="+1 (###) ###-####" mask="_"/> <br />
{data.TenantEmail}
</p>
</th>
<th>
Receipt Date: {moment().format("MM/DD/YYYY")}
</th>
</tr>
</Table>
<Table bordered>
<thead>
<tr>
<th className="text-center">Transaction Date</th>
<th className="text-center">Transaction Amount</th>
<th className="text-center">Currency Type</th>
</tr>
</thead>
<tbody>
<tr>
<td className="text-center">{moment(data.TransactionDate).format("MM/DD/YYYY")}</td>
<td className="text-center"><NumberFormat value={parseFloat(totalTransaction).toFixed(2)} displayType={'text'} thousandSeparator={true} prefix={'$'} /></td>
<td className="text-center">{data.PaymentType}</td>
</tr>
</tbody>
</Table>
</div>
</div>
</>
);
}
export default DepositReceipt;
【问题讨论】:
-
您可以使用@media print { your selectors here } 并在打印前显示。
-
你能举个例子吗?