【发布时间】:2021-02-25 11:39:17
【问题描述】:
我在 JSX 中使用三元运算符进行这些多项检查,同时在反应中进行条件渲染。一个问题是它必须定义 else 块,在这种情况下我有一个空字符串。这让我很困扰。有没有更好、更清洁的方法?
{order.productClass ? (
<li style={style.pLocation}>
<SettingsInputComponentIcon style={style.rightCardIcon} />
Product Class :
<label
style={{
marginLeft: 5,
color: "gray",
fontSize: "16px",
fontWeight: "normal",
}}
>
{order.productClass}
</label>
</li>
) : (
""
)}
我的组件中有多个这样的检查,这看起来不干净。
另一种方法是对项目使用 &&。
{order.deliveryTime && (
<li style={style.pLocation}>
<ScheduleIcon style={style.rightCardIcon} />
Dispatch Time :
<label
style={{
color: "gray",
fontSize: "16px",
fontWeight: "normal",
marginLeft: 5,
}}
>
{order.deliveryTime}
</label>
</li>
)}
有没有比上述更好、更清洁的方法?
【问题讨论】: