React - 如何打开 PDF 文件作为 href 目标空白

新手上路,请多包涵

这个在静态视图上相当简单的平凡任务,不符合 React。

有人可以告诉我如何在新选项卡上将 pdf 文件作为 href 打开吗?

这是我使用 react-bootstrap 和 react-router 的代码:

     <NavDropdown eventKey={3} title="Forms">

        <MenuItem eventKey={3.1} href="https://www.google.com/" target="_blank">Form 1</MenuItem>

        <MenuItem eventKey={3.2} href="samba.pdf" target="_blank">Form 2</MenuItem>
    </NavDropdown>

谷歌的外部链接工作正常。

pdf(保存在与上面的代码相同的目录中)没有。

当我点击 pdf 链接时,它会将我重定向到我的“404 catch all”路线。

     <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/contact" exact component={Contact} />
        <Route path="/about" exact component={About} />
        <Route component={NotFound} />
    </Switch>;

编辑: 这里的解决方案: 由 Link_Cable 回答

原文由 Jonca33 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 467
2 个回答

将 pdf 放入 /src 中的文件夹中。像组件一样导入它。将 href 参数设置为导入的 pdf 和 target = "_blank"

 import React, { Component } from 'react';
import Pdf from '../Documents/Document.pdf';

class Download extends Component {

  render() {

    return (
        <div className = "App">
          <a href = {Pdf} target = "_blank">Download Pdf</a>
        </div>
    );

  }
}

export default Download;

原文由 Erik Martín Jordán 发布,翻译遵循 CC BY-SA 4.0 许可协议

您也可以直接使用 require 函数:

 import React, { Component } from 'react';

    class Download extends Component {

      render() {

        return (
          <div className="App">
            <a href={require('../Documents/Document.pdf')} target="_blank">Download Pdf</a>
          </div>
        );
      }
    }

    export default Download;

原文由 Erik P_yan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题