javascript - 运行功能后在新选项卡中打开链接(.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>
任何建议将不胜感激。
解决方案
为什么不直接使用Window.open()
?获得文件的 URL 后,您可以在新窗口中打开它,而无需推送任何状态或以其他方式执行任何特定于 React 的操作。
推荐阅读
- javascript - 在选中单选按钮之前,必须禁用输入字段
- mysql - 从 sql 中的事件日志表获取步骤持续时间到累积快照事实的有效查询
- javascript - 如果 querySelector 不返回 null,则速记获取 textContent
- typescript - 如何在不使用 TypeORM 中的嵌入实体的情况下将类似的列添加到所有实体?
- model - 如何正确创建递归连接模型和相关输入字段以在 CakePHP 中编辑多连接表结构的数据?
- reactjs - 在 Jest 中使用上下文提供程序包装组件后“找不到存储”
- ruby - 内容类型响应不同
- javascript - 有没有一种好方法可以确保在移动使用它的代码之前创建一个对象?
- python - 匹配一段文本从开始到第一次出现的多字符子字符串
- java - 如何在 Java Swing 设计的桌面应用程序中存储静态变量?