[英]Conditional logic jsx react
I am trying to apply more than 1 condition to className in my jsx view. 我试图在我的jsx视图中对className应用1个以上的条件。 However it won't let me. 但是它不会让我。
It only listens to the first condition. 它仅侦听第一个条件。
className={usernameFocus ? "toggled" : "" || usernameValidated ? "validated" : ""}
I have tried several combinations: 我尝试了几种组合:
className={usernameFocus ? "toggled" : "" + usernameValidated ? "validated" : ""}
How could I accomplish more than one conditional to add classNames to my element? 我如何完成将classNames添加到元素的多个条件?
I think you are missing a space between the class names for when both are applied, also brackets help with multiple nested conditional statements. 我认为在同时应用两个类名时,您会在类名之间缺少空格,方括号也有助于多个嵌套的条件语句。
Try this: 尝试这个:
className={(usernameFocus ? "toggled" : "") + " " + (usernameValidated ? "validated" : "")}
Your order of operations is mixed up. 您的操作顺序是混乱的。 Put your separate conditions in parentheses. 将您的单独条件放在括号中。 Also, you can short-circuit the class evaluation like this: 同样,您可以像这样将类评估短路:
className={(usernameFocus && "toggled") + " " + (usernameValidated && "validated")}
If you feel extra fancy, you can also use a template string: 如果您觉得特别花哨,也可以使用模板字符串:
className={`${usernameFocus && "toggled"} ${usernameValidated && "validated"}`}
If you do this a lot (multiple booleans), have a look at the officially recommended classnames
module by Jed Watson. 如果您经常这样做(多个布尔值),请查看Jed Watson官方推荐的classnames
模块。 Link . 链接 。
With it, you can do it like this: 有了它,您可以这样做:
var usernameClasses = classNames({
'validated': usernameValidated,
'toggled': usernameFocus
});
className={usernameClasses};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.