繁体   English   中英

应用有条件的 CSS class 到 ReactJS 代码

[英]Applying conditional CSS class to ReactJS code

我觉得我按照文档正确地做,但它没有发生。 我知道有类似的问题,但不知何故我的代码不起作用。 它没有正确编译 class。

这是我的代码,如果用户角色正确,则可以点击。

<h4 
  onClick={(e) => {
    e.stopPropagation();
    if (this.props.role === 'owner' || this.props.role === 'member' || this.state.task.OwnerId === user_Proj.User.ID) {
      this.setState({MakeConfirm: true})
    }
  }}
  className="title {this.props.role === 'owner' ? 'owner__yes':'owner__no'}"
>
  Button
</h4>

output 未编译 CSS class。 这是需要修复的 output。

<h4 class="complete {this.props.role === 'owner' ? 'owner__yes':'owner__no'}">Button</h4>

这可以通过 JavaScript 的模板文字来实现:

<h4 
  className={`title ${this.props.role === 'owner' ? 'owner__yes':'owner__no'}`}
>
  Button
</h4>

问题是三元运算符没有被解析为 javascript 代码,因为它包含在双引号中。

改变

className="title {this.props.role === 'owner' ? 'owner__yes':'owner__no'}"

className={'title ' + (this.props.role === 'owner') ? 'owner__yes':'owner__no'}

注意this.props.role === 'owner'周围的括号。 它们很重要,因为如果您跳过括号, javascript 将首先将this.props.role'title'连接,然后检查连接的字符串是否等于'owner' 为避免此问题, this.props.role === 'owner'括在括号中。

如果您只想应用单个 className

<h4 className={this.props.role === 'owner' ? 'owner__yes' : '' }>Hello</h4>

如果您想应用一个 className 或另一个

<h4 className={this.props.role === 'owner' ? 'owner__yes' : 'owner_no' }>Hello</h4>

如果要应用固定的 className 和条件

<h4 className={`my-fixed-class ${this.props.role === 'owner' ? 'owner__yes' : 'owner_no' }`}>Hello</h4>

您还可以应用多个条件类名

<h4 className={`my-fixed-class ${this.props.role === 'owner' ? 'owner__yes' : this.props.role === 'employee' ? 'employee-yes' : 'customer' }`}>Hello</h4>

您也可以执行类似的操作,将字符串结果格式化为owner__yesowner__no

<h4 className={`owner__${this.props.role === 'owner' ? 'yes' : 'no' }`}>Hello</h4>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM