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

JSX中按语言循环条件渲染下载按钮问题排查

多语言PDF下载按钮的条件渲染解决方案

问题背景

现有多语言翻译数据结构如下:

[
    {
        "field": "name",
        "lang": "it",
        "text": "TEST"
    },
    {
        "field": "name",
        "lang": "en",
        "text": "TEST"
    },
    {
        "field": "pdf_url",
        "lang": "en",
        "text": ""
    },
    {
        "field": "pdf_url",
        "lang": "it",
        "text": "/var/www/vhosts/www.mar.com/IT-Codice-di-Condotta-NEW-20221213205852072761.pdf"
    }
]

需要针对英语(en)、意大利语(it)两种语言,分别判断对应pdf_url字段的文件是否存在,条件渲染各自的下载按钮。原代码使用find方法只能获取第一个匹配的pdf_url条目,无法实现多语言遍历渲染。

解决方法

  1. 从翻译数组中筛选出所有field为pdf_url的条目,再过滤出目标语言(en、it)的项;
  2. 遍历筛选后的条目,对每个语言的pdf_url单独做存在性校验,渲染对应的下载按钮或提示元素。

修改后的代码示例

{/* 定义支持的语言列表,方便后续扩展 */}
const supportedLangs = ['en', 'it'];

{/* 筛选并遍历目标语言的pdf_url条目 */}
document?.translations
  ?.filter(translation => translation.field === 'pdf_url' && supportedLangs.includes(translation.lang))
  ?.map(translation => {
    // 获取对应语言的名称文本
    const langName = document.translations.find(t => t.field === 'name' && t.lang === translation.lang)?.text;
    return (
      <div key={translation.lang} className="mb-3">
        {isDocumentUploaded(translation.text) ? (
          <DownloadButton 
            onClick={() => handleFileDownload(document.id, translation.lang, langName)}
          >
            {translation.lang === 'en' ? 'Download English Version' : 'Scarica Versione Italiana'}
          </DownloadButton>
        ) : (
          <p className='text-red-500 flex items-center'>
            <i className="ml-2 fa-lg text-red-500 fa-sharp fa-solid fa-circle-exclamation"></i>
            {translation.lang === 'en' ? 'No English document available' : 'Nessun documento italiano disponibile'}
          </p>
        )}
      </div>
    );
  })
}

代码说明

  • supportedLangs:统一管理支持的语言,后续新增语言只需修改此数组;
  • filter:精准筛选出目标语言的pdf_url条目,避免无效遍历;
  • map:遍历每个符合条件的语言项,为每个语言单独渲染组件;
  • 通过find匹配对应语言的name文本,保证下载函数参数的准确性;
  • 添加key属性确保React列表渲染的稳定性;
  • 为按钮和提示添加语言专属文本,优化用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:30:47