【问题标题】:Conditionally Applying class with ternary operator使用三元运算符有条件地应用类
【发布时间】:2017-11-09 11:06:14
【问题描述】:

我有一个 Button 组件,如果状态为“真”,我想为其分配一个活动类。

<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>

【问题讨论】:

  • 您在条件运算符处缺少:。也就是说,如果this.state.straightfalse,会发生什么?

标签: javascript html reactjs jsx


【解决方案1】:

你需要那里的错误表达式:

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

【讨论】:

  • 啊,就是这样。谢谢!
【解决方案2】:

如果您使用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>

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2010-09-18
      • 2010-09-28
      相关资源
      最近更新 更多