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

React中如何条件性完全省略aria-current属性

React中如何仅在当前步骤元素保留aria-current属性?

我在React中有如下HTML元素:

<p className={`
    cbds-c-progressStepper__stepText${step.state === 'complete' ? 
    "--complete" : ""}${step.state === 'current' ? 
    "--current" : ""}${step.state === 'incomplete' ? 
    "--incomplete" : ""}`
  }
  aria-current={`${step.state === 'current' ? 'step' : ''}`}
>

我希望仅在当前步骤的元素上保留aria-current属性,其他情况该属性需完全不存在。

我已尝试以下三种方法:

1) aria-current={`${step.state === 'current' ? 'step' : ''}`}
2) aria-current={`${step.state === 'current' ? 'step' : null}`}
3) 创建一个设为false的props并应用到该属性,按资料所述应能完全省略属性,但未成功。

方法1会生成无值的空aria-current属性,违反ADA合规要求;方法2会将其设为"null"字符串,均不符合需求。请问在React中如何实现该功能?


解决方案

在React中,当属性值为null或undefined时,该属性会被自动省略,不会渲染到DOM中。你之前的方法2出错是因为使用了模板字符串,把null转换成了字符串"null",而非真正的null值。

正确的写法有两种:

方法一:直接使用三元表达式返回undefined或null

<p 
  className={`
    cbds-c-progressStepper__stepText${step.state === 'complete' ? "--complete" : ""}
    ${step.state === 'current' ? "--current" : ""}
    ${step.state === 'incomplete' ? "--incomplete" : ""}`
  }
  aria-current={step.state === 'current' ? 'step' : undefined}
>

方法二:通过条件对象动态添加属性

如果需要处理多个条件属性,也可以用展开运算符:

const ariaProps = step.state === 'current' ? { 'aria-current': 'step' } : {};

<p 
  className={`
    cbds-c-progressStepper__stepText${step.state === 'complete' ? "--complete" : ""}
    ${step.state === 'current' ? "--current" : ""}
    ${step.state === 'incomplete' ? "--incomplete" : ""}`
  }
  {...ariaProps}
>

这两种写法都会在step.state不为current时,完全省略aria-current属性,符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:15:59