You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据HTML的lang属性实现不同文件的下载?

根据HTML lang属性切换下载文件的解决方案

这里有两种简洁的实现方式,适配你的React+i18next场景:

方法1:直接动态绑定a标签的href属性

利用React变量直接计算对应语言的文件地址,无需额外函数,最适合你的现有代码结构:

import { useTranslation } from "react-i18next";
import ENCV from "../assets/englishCV.pdf";
import PTCV from "../assets/portugueseCV.pdf";

const CTA = () => {
    const { t, i18n } = useTranslation();
    // 用react-i18next的当前语言(和html的lang同步),比手动操作DOM更可靠
    const cvUrl = i18n.language === "pt" ? PTCV : ENCV;

    return(
        <div className="cta">
            <a href={cvUrl} download className="btn">{t("downloadCV")}</a>
            <a href="#contact" className="btn btn-primary">{t("contactButton")}</a>
        </div>
    );
};

export default CTA;

如果一定要严格读取HTML标签的lang属性,把i18n.language替换成document.documentElement.lang即可:

const htmlLang = document.documentElement.lang;
const cvUrl = htmlLang === "pt" ? PTCV : ENCV;

方法2:通过点击函数触发下载(适合需额外逻辑的场景)

如果需要在下载前做校验、日志等操作,可以用函数动态创建下载链接:

import { useTranslation } from "react-i18next";
import ENCV from "../assets/englishCV.pdf";
import PTCV from "../assets/portugueseCV.pdf";

const CTA = () => {
    const { t } = useTranslation();

    const onDownloadCV = () => {
        const htmlLang = document.documentElement.lang;
        const cvUrl = htmlLang === "pt" ? PTCV : ENCV;
        // 创建临时a标签触发下载
        const downloadLink = document.createElement('a');
        downloadLink.href = cvUrl;
        // 可选:自定义下载文件名,提升用户体验
        downloadLink.download = htmlLang === "pt" ? "curriculo.pdf" : "cv.pdf";
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
    };

    return(
        <div className="cta">
            <button onClick={onDownloadCV} className="btn">{t("downloadCV")}</button>
            <a href="#contact" className="btn btn-primary">{t("contactButton")}</a>
        </div>
    );
};

export default CTA;

注意事项

  • 如果你使用react-i18next的语言切换功能,优先用i18n.language,它会自动和HTML的lang属性同步,避免手动操作DOM带来的不一致问题。
  • 自定义下载文件名时,download属性的值会覆盖文件原有名称,让用户更清楚下载的内容。

内容的提问来源于stack exchange,提问作者Caio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 04:45:31