【发布时间】:2022-06-18 19:46:23
【问题描述】:
我有一个自定义的<Button /> 组件,其styled-component 中的属性如color、hasBorder 和outlined
如果我像这样执行if 语句,它正在评估default 案例
border: ${({ theme, color, hasBorder, outlined }) => {
switch (true) {
case outlined && hasBorder && !color:
return `1px solid ${theme.text}`;
case outlined && hasBorder && color:
return `1px solid ${color}`;
default:
return "1px solid transparent";
}
}};
但如果我这样做,效果很好
border: ${({ theme, color, hasBorder, outlined }) => {
switch (true) {
case outlined !== undefined &&
hasBorder !== undefined &&
hasBorder &&
color === undefined:
return `1px solid ${theme.text}`;
case outlined !== undefined &&
hasBorder !== undefined &&
hasBorder &&
color !== undefined:
return `1px solid ${color}`;
default:
return "1px solid transparent";
}
}};
我不确定这里发生了什么,有什么想法吗?
【问题讨论】:
-
开关盒是
boolean这里。所以你没有超过 2 个案例:true,false。不保证任何一个 switch case 是 true 或 false。为什么不直接使用if语句而不使用switch? -
我会试试的,我使用
switch语句,因为它通常更快,但我认为我过度考虑了性能,如果我错了请纠正我 -
switch优先于if-else如果有更多情况,例如12个月中的一个月。但在这种情况下,只有两种可能的情况:true或false。所以最好选择if-else。另请注意,在使用switch时,所有情况都应该不同,但在这种情况下,情况似乎并没有什么不同 -
似乎是这样工作的