如何有条件地添加一个类名?

How to conditionally add a className?

我有以下 react-redux-form:

<fieldset>
  <label>{label}</label>
  <div>
    <input {...input} name="email" type="text" className="form-control" />
    {touched && error && <span className="error">{error}</span>}
  </div>
</fieldset>

我希望能够使用

更新 <fieldset>
className=""
className="has-success"
className="has-danger"

逻辑是:

我怎样才能让它在 React 中工作?

你可以这样实现它:

<fieldset className={touched ? (error ? "has-danger" : "has-success") : ""}> 
  ... 
</fieldset>

这首先检查 touched 是否为真。如果是,那么它只会呈现 <fieldset>,如果 error 为真,则 class 将为 "has-danger",否则为 "has-success"。如果 touched 不存在 ,则 class 为空字符串。这假定不会出现 touched 为假且 error 为真的情况(尽管您可以添加更多内容来处理这种情况)。

如果您发现这有点不可读,也许可以尝试使用更具可读性的 classnames NPM 包:

<fieldset className={classNames({
  "": !touched && !error,
  "has-danger": touched && error,
  "has-success": touched && !error
})}>
  ...
</fieldset>

这更具可读性并且不假设不会出现 touched 为假且 error 为真的情况