我想根据具体情况给div一个css类。它总是需要最后的条件。
这是我的代码。
我得到logos.length
为3
<div className= "${ (this.state.logos && (this.state.logos.length == 3)) ? 'width_15_percent' : (this.state.logos && (this.state.logos.length == 2)) ? 'width_20_percent' : 'width_50_percent' } ">
some data
</div>
任何帮助都会很棒。
谢谢。
< div className = {
(this.state.logos && (this.state.logos.length === 3)) ? 'width_15_percent' :
(this.state.logos && (this.state.logos.length === 2)) ? 'width_20_percent' : 'width_50_percent'
} >
some data < /div>
这里不需要引号和$符号。直接传递你的表达。
<div className={ (this.state.logos && (this.state.logos.length == 3)) ? 'width_15_percent' : (this.state.logos && (this.state.logos.length == 2)) ? 'width_20_percent' : 'width_50_percent' }>
some data
</div>
<div className={ (this.state.logos && (this.state.logos.length == 3)) ? 'width_15_percent' : (this.state.logos && (this.state.logos.length == 2)) ? 'width_20_percent' : 'width_50_percent' }>
some data
</div>
如果你使用String Literal($),那么你应该用`替换'
<div className= `${ (this.state.logos && (this.state.logos.length ==
3)) ? 'width_15_percent' : (this.state.logos &&
(this.state.logos.length == 2)) ? 'width_20_percent' :
'width_50_percent' }`>
some data
</div>
只是建议使用classnames - 它是一个非常简单但有效的工具来加入类名或按条件设置
这里有一个很棒的管理类包:https://www.npmjs.com/package/classnames/
它很容易使用
首先你必须安装,然后导入喜欢
import classNames from 'classnames'
<div className={classNames('yourClassName', { width_15_percent: this.state.logos.length == 3})}>
将应用类“width_15_percent”您的条件为真
或者如果你不想使用包装,那就去吧
<div className={`yourClassName ${(this.state.logos.length == 3) ? 'width_15_percent' : '' }`}>
为了便于阅读,创建一个只返回正确类而不是编写所有这些双三元运算符的方法。你可以这样做:
getClassName() {
let width = null;
switch (this.state.logos.length) {
case 2:
width = 20
break;
case 3:
width = 15;
break;
default:
width = 50;
break;
};
return `width_${width}_percent`;
}
render() {
return (
<div className={this.getClassName()}>
)
}