【发布时间】:2020-11-19 15:06:46
【问题描述】:
我收到此错误:TypeError: Cannot read property 'setState' of undefined
当我尝试使用 @react-pdf/renderer 包在 pdf 中显示输入值时。
错误完全在:{this.setState.title} 行
有人可以告诉我是什么原因导致我的情况出现此错误,提前谢谢您。
这是我的代码:
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
}
});
// Create Document Component
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>{this.setState.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:
<PDFDownloadLink
document={<MyDocument/>}
fileName="doc.pdf">
{({ blob, url, loading, error }) => (
loading ? 'Loading...' : 'Download!'
)}
</PDFDownloadLink>
</div>
);
}
}
export default Form;
【问题讨论】: