首页 > 解决方案 > 运行功能后在新选项卡中打开链接(.pdf 文件)且不更改路线

问题描述

在我的反应应用程序中,运行返回文件路径的函数后,我需要在新选项卡中显示一个 pdf文件。

到目前为止,我所做的是使用一个带有 onClick 事件的简单 div,该事件触发了上述功能,当我从后端获取文件的路径时,我使用的是 this.props.history.push(/'PDF')并推送到 PDF 组件,顺便说一下:

 render() {
    return (
        <Iframe
          url={`${process.env.REACT_APP_NODE_SERVER}/${this.props.PDFFilename}`}
          position="absolute"
          width="100%"
          id="myId"
          height="100%"
          />
    );
  }

我还使用了运行良好的 react-new-window,它确实在新窗口中打开了 pdf 组件,但是由于我仍然使用 this.props.history.push,所以 react 应用程序仍然会更改路由,这是不可取的。

然后,我使用了 Link 组件(来自 react-router-dom)。这里的问题是链接在函数运行之前被触发,以一个空的新选项卡结束。这就是我使用链接组件的方式:

<Link to=/PDF target="_blank">
<img className="print-dropdown" src={print} alt="print" />
<span onClick={() =>
   printCons(
     this.props.username,
     this.props.password,
     "A4",
     this.props.consignmentNo,
     this.props.updatePDFFilename,
    )
   }
>
  A4
 </span>
</Link>

任何建议将不胜感激。

标签: javascriptreactjs

解决方案


为什么不直接使用Window.open()?获得文件的 URL 后,您可以在新窗口中打开它,而无需推送任何状态或以其他方式执行任何特定于 React 的操作。


推荐阅读