我收到此错误:TypeError:
当我尝试使用@ react-pdf / renderer包在pdf中显示输入值时,无法读取未定义的属性“ setState”。
错误完全在:{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;
现在的问题是在功能组件中使用它
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>{this.setState.title}</Text> /// this point
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
您应该将此值作为对此组件的支持传递给
const MyDocument = (props) => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>{props.title}</Text> /// this point
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
并通过标题作为道具
<PDFDownloadLink
document={<MyDocument title={this.state.title}/>}
fileName="doc.pdf">
{({ blob, url, loading, error }) => (
loading ? 'Loading...' : 'Download!'
)}
</PDFDownloadLink>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句