在 reactjs 中显示 PDF 文件

Displaying PDF files in reactjs

我是 React 的新手,我正在尝试从存储在 src 目录中的 link 个 PDF 的 select 可用列表中显示一个 PDF。对于 PDF 查看,我使用了此处的代码:https://npm.io/package/react-pdf

Image of my display page

所以我在屏幕的左半边有一个小 table,如果我 select 其中一个 link 它应该在屏幕的右侧打开 pdf屏幕。 我只设法将 <ViewPdf/> 函数与一个已经硬编码的 pdf 文件放在一起,这就是我在右侧显示它的方式。

我的问题是如何实现这样一种情况,我可以从 table 中单击 link 并在右侧显示文件。 这是我的代码:

import ViewPdf from '../../../components/ViewPdf'
import {Table,Col,Row,Button} from 'reactstrap'

const DocTable = () => {
  return (
    <>
      <span style={{ fontWeight: 'bold' }}>Documents</span><br/>
    <Table bordered hover size="sm">
      <thead>
        <br/>
        <tr>
          <th>ID</th>
          <th>Document Name</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">1-86</th>
          <td><Button color="link">Medical Insurance Claim</Button></td>
          <td>Signed</td>
        </tr>
        <tr>
          <th scope="row">0-34</th>
          <td><Button color="link">Household Insurance</Button></td>
          <td>Signed</td>
        </tr>
        <tr>
          <th scope="row">2-24</th>
          <td><Button color="link">Car Insurance</Button></td>
          <td>Not Signed</td>
        </tr>
      </tbody>
    </Table>
    <br/>
    </>
  );
}

const DocumentList=()=>{

    return (
      <div>
        <Row>
        <Col xs="6">
          {DocTable()}
        </Col>

        <Col xs="6">
       <ViewPdf/>
        </Col>
      </Row>
      </div>
    );
  
}
export default DocumentList

首先,您需要一个带有处理函数的按钮来在 hide/show 情况之间切换。另外,需要一个状态变量来存储当前情况:

const DocTable = ({isVisible, onToggle}) => {
  return (
    <>
     // ... rest of the codes

     <button onClick={onToggle}>
       {isVisible? "Hide" : "Show"}
     </button>

     // ... rest of the codes
    </>
  );
}

现在将基本部分添加到 DocTable 组件,返回到 DocumentList 组件并实现状态和处理程序:

import React, {useState} from 'react';

const DocumentList= () => {
   const [isVisible, setIsVisible] = useState(false) // false to hide the PDF for the first time

   const handleToggle = () => {
     setIsVisible(prevState => !prevState)
   }
   
    return (
      <div>
        <Row>
        <Col xs="6">
          <DocTable isVisible={isVisible} onToggle={handleToggle}/>
        </Col>

        <Col xs="6">
          { isVisible && <ViewPdf/> }
        </Col>
      </Row>
      </div>
    );
}

现在,单击 DocTable 组件上的按钮,handleToggle 函数将调用并更改 isVisible 值,最后 isVisible 变量确定为是否显示 ViewPdf 个组件。