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

React JSX如何避免嵌套三元表达式报错 实现三种条件样式渲染

实现方案

以下几种方式都可以避免嵌套三元的ESLint报错,同时实现你需要的逻辑:


方案1(最推荐):抽离独立渲染函数

把条件判断逻辑从JSX模板中抽离为组件内独立方法,可读性更高,后续维护修改也更方便:

// 组件内单独定义渲染方法
const renderExtraContent = () => {
  // 满足followed直接返回空,提前结束判断
  if (followed) return null
  if (!opened) {
    return <div id={styles.themeBox}><p>+10</p></div>
  }
  return <img 
    src={arrowDownIcon} 
    alt="" 
    style={{
      height:'1.2em', 
      marginRight:'10px', 
      width:'auto', 
      objectFit:'contain'
    }} 
  />
}

// JSX模板中直接调用方法
<div className={styles.extraContainer}>
  {renderExtraContent()}
</div>

方案2:单层三元配合逻辑与

你的三个分支有统一的前置判断条件!followed,可以先判断这个条件,再处理opened分支,完全不需要嵌套三元:

<div className={styles.extraContainer}>
  {!followed && (
    !opened ? 
      <div id={styles.themeBox}><p>+10</p></div> :
      <img 
        src={arrowDownIcon} 
        alt="" 
        style={{
          height:'1.2em', 
          marginRight:'10px', 
          width:'auto', 
          objectFit:'contain'
        }} 
      />
  )}
</div>

方案3:修正原IIFE写法

你之前写的立即执行函数本身是合法写法,只是遗漏了return语句导致内容无法渲染,补全后可以正常运行:

<div className={styles.extraContainer}>
  {
    (() => {
      if (!opened && !followed )
        return <div id={styles.themeBox}><p>+10</p></div>
      else if (opened && !followed)
        return <img 
          src={arrowDownIcon} 
          alt="" 
          style={{
            height:'1.2em', 
            marginRight:'10px', 
            width:'auto', 
            objectFit:'contain'
          }} 
        />
      return null
    })()
  }
</div>

小提示:你原有代码中style属性里的marginLRight是拼写错误,正确属性名是marginRight。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:18:02