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

使用@react-pdf/renderer时出现setState未定义错误求排查

解决@react-pdf/renderer中TypeError: Cannot read property 'setState' of undefined的问题

咱们来一步步拆解你遇到的问题,然后给出明确的修复方案:

错误原因分析

你碰到的报错主要源于三个核心问题:

  • 函数组件无this对象:你的MyDocument是一个函数组件,函数组件内部不存在this上下文,直接写this.setState时,this本身就是undefined,自然会抛出"无法读取undefined的setState属性"的错误。
  • 混淆setState与state的用途:就算是类组件,setState是用来更新状态的方法,读取状态应该用this.state,你错误地用this.setState.title来读取值,本身用法就不符合React的状态规范。
  • 状态未传递到子组件:Form组件里的title状态没有传递给MyDocument,所以就算前面的问题解决了,MyDocument也拿不到输入框的内容。

修复方案

我们分三步修正代码:

1. 让MyDocument接收props并正确读取值

把MyDocument改成接收title props的函数组件,用props.title(或解构后的title)来获取输入框内容:

// 用解构赋值简化props读取
const MyDocument = ({ title }) => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        {/* 直接用解构后的title渲染 */}
        <Text>{title}</Text>
      </View>
      <View style={styles.section}>
        <Text>Section #2</Text>
      </View>
    </Page>
  </Document>
);

2. 在Form组件中传递title状态给MyDocument

在PDFDownloadLink的document属性里,把Form的title状态作为props传给MyDocument:

<PDFDownloadLink document={<MyDocument title={this.state.title}/>} fileName="doc.pdf">
  {({ blob, url, loading, error }) => (
    loading ? 'Loading...' : 'Download!'
  )}
</PDFDownloadLink>

完整修复后的代码

import React, { Component } from 'react';
import { PDFDownloadLink, Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';

const styles = StyleSheet.create({
  page: { flexDirection: 'row', backgroundColor: '#E4E4E4' },
  section: { margin: 10, padding: 10, flexGrow: 1 }
});

// 修正后的MyDocument:接收title props并正确渲染
const MyDocument = ({ title }) => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        <Text>{title}</Text>
      </View>
      <View style={styles.section}>
        <Text>Section #2</Text>
      </View>
    </Page>
  </Document>
);

class Form extends Component {
  state = { title: '', url: null };

  onChange = input => e => {
    this.setState({ [input]: e.target.value });
  }

  onRender = ({ blob }) => {
    this.setState({ url: URL.createObjectURL(blob) });
  };

  render() {
    return (
      <div>
        <input 
          onChange={this.onChange('title')} 
          name="title" 
          type="text" 
          placeholder="Post Title" 
          className="form-control" 
        />
        Download your PDF here:
        {/* 传递title状态给MyDocument */}
        <PDFDownloadLink document={<MyDocument title={this.state.title}/>} fileName="doc.pdf">
          {({ blob, url, loading, error }) => (
            loading ? 'Loading...' : 'Download!'
          )}
        </PDFDownloadLink>
      </div>
    );
  }
}

export default Form;

这样修改后,输入框的内容就能正确传递到PDF文档里,也不会再出现setState相关的错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:32:40