问题描述
我在 react-redux-form 中有以下内容:
<label>{label}</label><div><input {...input} name="email" type="text" className="form-control"/>{感动&&错误&&<span className="error">{error}</span>}
我在 react-redux-form 中有以下内容:
<label>{label}</label><div><input {...input} name="email" type="text" className="form-control"/>{感动&&错误&&<span className="error">{error}</span>}
</fieldset>
我希望能够使用任何一个
更新
className=""className="已成功"类名=有危险"
逻辑是:
touched
但没有error
:
touched
和error
:
touched
也没有 error
:
如何在 React 中实现此功能?
你可以这样实现:
...</fieldset>
这首先检查 touched
是否为真.如果是,那么它才会呈现 哪个类将是
"has-danger"
如果 error
为真或 "has-success"
否则.如果touched
,不存在,那么这个类就是一个空字符串.这假设不会出现 touched
为假而 error
为真的情况(尽管您可以添加更多来处理这种情况).
如果您发现这有点难以理解,可以尝试使用 classnames
更具可读性的 NPM 包:
这更具可读性并且不假设不会出现
touched
为假而error
为真的情况.
I have the following with 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>
I would like to be able to update
<fieldset>
with either
className=""
className="has-success"
className="has-danger"
The logic would be:
If touched
but no error
: <fieldset className="has-success">
If touched
and error
: <fieldset className="has-danger">
If not touched
nor error
: <fieldset className="">
How can I get this working in React?
解决方案
You could implement it like so:
<fieldset className={touched ? (error ? "has-danger" : "has-success") : ""}>
...
</fieldset>
This first checks if
touched
is truthy. If it is, only then will it render a <fieldset>
which class will be "has-danger"
if error
is truthy or "has-success"
otherwise. If touched
, doesn't exist, then the class is an empty string. This assumes that there will be no case where touched
is falsey and error
is truthy (though you could add more to handle that case).
If you find that this is a bit unreadable, maybe try using the
classnames
NPM package which is a bit more readable:
<fieldset className={classNames({
"": !touched && !error,
"has-danger": touched && error,
"has-success": touched && !error
})}>
...
</fieldset>
This is more readable and doesn't assume there won't be a case where
touched
is falsey and error
is truthy.
这篇关于如何有条件地添加类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-04 06:28