英文:
Download a file from navbar using the "download" attribute with HashRouter (React.js)
问题
我有一个导航栏,当点击其中一个元素时,我希望能够下载存储在我的存储库的公共目录中的文件。
我正在使用来自react-router-dom
的HashRouter
。
通常情况下,我们会使用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 'react-router-dom'
.
Normally we would use Link
from 'react-router-dom'
:
<Link
key={section.name}
to={section.link}
download={section.link === '/myfile.txt' ? 'myfile.txt' : undefined}
>
{section.name}
</Link>
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 <a>
tag instead, but had to manually add #
for the other navbar elements for navigation :
<a
key={section.name}
href={section.link === '/myfile.txt' ? section.link : `#${section.link}`}
download={section.link === '/myfile.txt' ? 'myfile.txt' : undefined}
>
{section.name}
</a>
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 }) => {
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论