You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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')错误。

修复步骤

  1. 修正测试数据格式
    将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"
};
  1. 修正布局宽度溢出问题
    你当前设置三个表头列宽度各为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>
  1. 修正未用Text组件包裹文本的问题
    代码末尾的Thank you for your business!直接写在View组件内,react-pdf不支持这种写法,需改为:
<Text>Thank you for your business!</Text>
  1. 新增空值兜底逻辑
    所有读取invoice、user属性的位置加上可选链,避免字段为空时触发报错,示例:
<Text>{invoice?.clientName || ""}</Text>
<Text>{moment(invoice?.sentDate).format("Do MMMM YYYY")}</Text>
{invoice?.tasks?.map((task) => {
  // 原有映射逻辑
})}

内容的提问来源于stack exchange,提问作者aa webdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:06:04