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

Jon*_*a33 9 javascript reactjs react-bootstrap react-router

这个在静态视图上相当简单的平凡任务不符合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> 
Run Code Online (Sandbox Code Playgroud)

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

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>;
Run Code Online (Sandbox Code Playgroud)

编辑: 解决方案: Link_Cable回答

Eri*_*dán 14

将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;
Run Code Online (Sandbox Code Playgroud)

  • 以防万一有人偶然发现同样的问题:我将 React 与 Typescript 一起使用,并且无法将“.pdf”文件作为模块导入。我可以用更多的配置来做到这一点:在`custom.d.ts`中,我只是添加了:```declare module '*.pdf' { const content: any; 导出默认内容;}``` 那时解决方案就起作用了。 (8认同)