使用HashRouter(React.js)和“download”属性从导航栏下载文件。

huangapple go评论64阅读模式
英文:

Download a file from navbar using the "download" attribute with HashRouter (React.js)

问题

我有一个导航栏,当点击其中一个元素时,我希望能够下载存储在我的存储库的公共目录中的文件。
我正在使用来自react-router-domHashRouter

通常情况下,我们会使用react-router-dom中的Link

    <Link
      key={section.name}
      to={section.link}
      download={section.link === '/myfile.txt' ? 'myfile.txt' : undefined}
    >
      {section.name}
    </Link>

但是下载不起作用(找不到文件),尽管文件位于公共文件夹中。

作为这个问题的临时解决方案,我改用了<a>标签,但必须手动为其他导航栏元素添加#以进行导航:

    <a
      key={section.name}
      href={section.link === '/myfile.txt' ? section.link : `#${section.link}`}
      download={section.link === '/myfile.txt' ? 'myfile.txt' : undefined}
    >
      {section.name}
    </a>

我的问题是如何使用Link标签来实现这个功能?

英文:

I have a navbar and I want one of its elements to download a file that is in the public directory of my repo when clicking on it.
I'm using HashRouter from &#39;react-router-dom&#39;.

Normally we would use Link from &#39;react-router-dom&#39; :

    &lt;Link
      key={section.name}
      to={section.link}
      download={section.link === &#39;/myfile.txt&#39; ? &#39;myfile.txt&#39; : undefined}
    &gt;
      {section.name}
    &lt;/Link&gt;

But the download doesn't work (file not found) knowing that the file is in the public folder.

As a temporary solution to this problem, I used the &lt;a&gt; tag instead, but had to manually add # for the other navbar elements for navigation :

    &lt;a
      key={section.name}
      href={section.link === &#39;/myfile.txt&#39; ? section.link : `#${section.link}`}
      download={section.link === &#39;/myfile.txt&#39; ? &#39;myfile.txt&#39; : undefined}
    &gt;
      {section.name}
    &lt;/a&gt;

My question is how can I do it with the Link tag?

答案1

得分: 1

我建议创建一个自定义链接组件,根据是否存在任何“download”属性来有条件地呈现一个“Link”组件或“a”元素。

示例:

const CustomLink = ({ children, download, to, ...props }) => {
  return download
    ? <a href={to} download={download} {...props}>{children}</a>
    : <Link to={to} {...props}>{children}</Link>;
};
<CustomLink
  key={section.name}
  to={section.link}
  download={section.download}
>
  {section.name}
</CustomLink>
英文:

I would recommend creating a custom link component that conditionally renders either a Link component or a element depending on the presence of any download prop.

Example:

const CustomLink = ({ children, download, to, ...props }) =&gt; {
  return download
    ? &lt;a href={to} download={download} {...props}&gt;{children}&lt;/a&gt;
    : &lt;Link to={to} {...props}&gt;{children}&lt;/Link&gt;;
};
&lt;CustomLink
  key={section.name}
  to={section.link}
  download={section.download}
&gt;
  {section.name}
&lt;/CustomLink&gt;

huangapple
  • 本文由 发表于 2023年1月9日 04:46:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定