react-pdf/renderer报Cannot read properties of undefined (reading 'height')如何解决
核心报错原因
你传入InvoicePage组件的invoice参数类型不匹配:DashboardScreen中定义的测试数据viewInvoice = [""]是字符串数组,但InvoicePage全程将invoice当做对象读取属性(如invoice.clientName、invoice.tasks等),数组上不存在这些属性,最终导致react-pdf计算元素布局高度时抛出Cannot read properties of undefined (reading: 'height')错误。
修复步骤
- 修正测试数据格式
将DashboardScreen中的viewInvoice修改为符合字段要求的对象,示例:
const viewInvoice = { clientName: "测试客户", clientAddrOne: "测试地址1", clientCity: "测试城市", clientPostcode: "100000", invoiceNumber: "INV2024001", sentDate: new Date(), dueDate: new Date(Date.now() + 7*24*60*60*1000), tasks: [ { taskDescription: "测试任务", hours: 2, minutes: 30 } ], hourlyRate: 100, paymentMethod: "银行转账", accountNumber: "12345678", sortCode: "12-34-56" };
- 修正布局宽度溢出问题
你当前设置三个表头列宽度各为35%,总和超过100%会导致布局溢出,调整宽度分配总和控制在100%以内即可,示例:
<Text style={{ width: "33%", textDecoration: "underline" }}> Invoice Number </Text> <Text style={{ width: "33%", textDecoration: "underline" }}> Date Sent </Text> <Text style={{ width: "34%", textDecoration: "underline" }}> Date Due </Text>
- 修正未用Text组件包裹文本的问题
代码末尾的Thank you for your business!直接写在View组件内,react-pdf不支持这种写法,需改为:
<Text>Thank you for your business!</Text>
- 新增空值兜底逻辑
所有读取invoice、user属性的位置加上可选链,避免字段为空时触发报错,示例:
<Text>{invoice?.clientName || ""}</Text> <Text>{moment(invoice?.sentDate).format("Do MMMM YYYY")}</Text> {invoice?.tasks?.map((task) => { // 原有映射逻辑 })}
内容的提问来源于stack exchange,提问作者aa webdev
相关产品推荐
相关产品推荐

