我目前有功能组件:

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为假,则不添加任何类。如果不是pristinetouchederror,则添加"has-danger"。如果不是pristinetouched和否error,则添加"has-success"。您甚至可以摆脱第一个条件,因为这有点用处,并添加您自己的案例。

10-08 08:01
查看更多