不要嵌套三元表达式 - 根据条件在 3 种样式之间切换的方法
Do not nest ternary expressions - Way to change between 3 styles based on coditions
我正在尝试根据条件显示 3 种不同的样式,但我无法使用三元表达式来实现。我找到了一些解决方案 但仍然遇到一些问题。
以下条件是我想做的:
<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>
因为当我尝试以下代码时,我收到 不要嵌套三元表达式。 错误。
{!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'}} /> : ""}
我认为最好的可读解决方案是:
<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>
我正在尝试根据条件显示 3 种不同的样式,但我无法使用三元表达式来实现。我找到了一些解决方案
以下条件是我想做的:
<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>
因为当我尝试以下代码时,我收到 不要嵌套三元表达式。 错误。
{!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'}} /> : ""}
我认为最好的可读解决方案是:
<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>