【问题标题】:Do not nest ternary expressions - Way to change between 3 styles based on coditions不要嵌套三元表达式 - 根据条件在 3 种样式之间进行更改的方法
【发布时间】:2021-12-14 07:46:59
【问题描述】:

我正在尝试根据代码显示 3 种不同的样式,但我无法使用三元表达式来实现。我找到了一些解决方案here,但仍然遇到了一些问题。
以下条件是我想做的:

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

因为当我尝试以下代码时,我收到 Do not nest ternary expressions. 错误。

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

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    我认为最好的可读解决方案是:

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

    或者你可以嵌套条件:

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

    【讨论】:

    • 第一个解决方案解决了我的问题,谢谢!但不是嵌套条件的第二种解决方案,&lt;&gt; 和 &lt;/&gt; 是什么意思?
    • > 是 的简短语法 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2017-11-22
    • 2012-01-12
    • 1970-01-01
    • 2022-08-16
    • 2016-03-08
    • 1970-01-01
    相关资源
    最近更新 更多