有条件地应用 class 与三元运算符

Conditionally Applying class with ternary operator

我有一个 Button 组件,如果状态为 'true',我想为其分配一个活动的 class。

<Button 
    onClick={this.preferenceHandler.bind(this, "straight")}  
    className={"col-sm-12 text-center " + (this.state.straight ? "active") }
    viewStyle=  "primary"
>
    <h4>Straight</h4>
    <i className="icon icon-ok-6"></i>
</Button>

你需要里面的假表达式:

className={"col-sm-12 text-center " + (this.state.straight ? "active" : "") }

如果使用 classnames

,则使用条件 类 会更好
var btnClass = classNames({
  'col-sm-12': true,
  'text-center': true,
  'active': this.state.straight
});
<Button 
    onClick={this.preferenceHandler.bind(this, "straight")}  
    className={btnClass}
    viewStyle="primary"
>
    <h4>Straight</h4>
    <i className="icon icon-ok-6"></i>
</Button>

与@rossipedia 类似,但使用 ES6 模板字符串

className={`col-sm-12 text-center ${this.state.straight ? 'active' : ''}`}