我在JSX中使用三元操作符进行这些多重检查,同时在react中进行条件渲染。一个问题是它必须定义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>
)}
有没有比前面提到的更好、更干净的方法?
你绝对可以利用&&
Ternary Operator
是有意义的,当你需要有一个Loading状态
当有很多移动的棋子时,If..Else
是有意义的。
同时,尽量使事物模块化。将帮助你组织你的组件,使东西更容易读,并在一定程度上有助于调试。
我希望这能回答你的问题:)
我发现这个方法看起来更简洁。
<div style={{ display: order.deliveryTime ? '' : 'none' }}>
<li style={style.pLocation}>
<ScheduleIcon style={style.rightCardIcon} />
Dispatch Time :
<label
style={{
color: "gray",
fontSize: "16px",
fontWeight: "normal",
marginLeft: 5,
}}
>
{order.deliveryTime}
</label>
</li>
</div>
这是使用css显示属性。如果有交付时间,则显示内容,否则不显示。