我目前有功能组件:
let renderEmailField = ({input, label, type, meta: {touched, error, pristine}}) =>
<fieldset className=????
.....
我目前正在使用此三元表达式有条件地添加一个类:
<fieldset className={touched ? (error ? "has-danger" : "has-success") : ""}>
上面的问题是它没有考虑新的
pristine
属性,如果pristine
为true,则不应添加"has-success"
,因为用户没有做任何事情。如何更新上述
className
逻辑,以仅在"has-danger"
为false时添加"has-success"
或pristine
? 最佳答案
我同意使用三元运算符不是最好的。您可以使用一些if
语句进行设置,但是我发现使用classnames
包(它也可以是内联的)更为简洁。当前,您现在使用classnames
编写的代码如下所示:
<fieldset className={classNames({
"": !touched && !error,
"has-danger": touched && error,
"has-success": touched && !error
})}>
...
</fieldset>
您可以像下面这样更改
"has-danger"
和"has-success"
的条件以说明pristine
:<fieldset className={classNames({
"": !touched && !error,
"has-danger": !pristine && touched && error, //you could cache !prinstine && touched as to not have duplicate code
"has-success": !pristine && touched && !error
})}>
...
</fieldset>
对于要添加的每个潜在类,您都描述了要添加的某个条件。如果
touched
为真,而error
为假,则不添加任何类。如果不是pristine
,touched
和error
,则添加"has-danger"
。如果不是pristine
,touched
和否error
,则添加"has-success"
。您甚至可以摆脱第一个条件,因为这有点用处,并添加您自己的案例。