首页 > 解决方案 > React 不会编译我尝试使用 react-pdf 的组件

问题描述

我一直在阅读 React 和 React-pdf 的官方文档,以及博客、视频,但我仍然看不到是什么导致 React 抛出编译错误。

PDF.js

import React from 'react';
import { Page, Text, View, Document, StyleSheet} from '@react-pdf/renderer'
import '../styles/PDF.css';

const PDF = () => {

    <div>
        <Document> 
            <Page size="A4" id="page">
                <View className="view">
                    <Text className="text">First section of the PDF document</Text>
                </View>
                <View className="view">
                    <Text className="text">Second section of the PDF document</Text>
                </View>
            </Page>
        </Document>
    </div>

}

export default PDF;

当我将它直接导入 index.js 时,它会引发编译错误。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './styles/index.css';
import PDF from './components/PDF.js';

ReactDOM.render(<PDF />,document.getElementById('root')
);

错误

编译失败。

./src/components/PDF.js

期望一个赋值或函数调用,而是看到一个表达式。

任何帮助将不胜感激。

标签: javascriptreactjs

解决方案


您忘记在 PDF.js 文件中返回 JSX。

import React from 'react';
import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer';
import '../styles/PDF.css';

const PDF = () => {
  return (
    <div>
      <Document>
        <Page size="A4" id="page">
          <View className="view">
            <Text className="text">First section of the PDF document</Text>
          </View>
          <View className="view">
            <Text className="text">Second section of the PDF document</Text>
          </View>
        </Page>
      </Document>
    </div>
  );
};

export default PDF;

推荐阅读