react设置多个className

在一个元素上设置样式,有一个固定的样式,然后还有一个使用三元运算符根据条件添加的样式。

1
2
3
4
5
6
比如说有一个固定样式"title":
<div className="title">标题</div>,
然后还要一个点击高亮的样式:
<div className={index === this.state.active ? "active" : null}>标题</div>
不能这样写:
<div className="title" className={index === this.state.active ? "active" : null}>标题</div>

  

方法一:ES6 模板字符串 ``

1
className={`title ${index === this.state.active ? 'active' : ''}`}

  

方法二:join("")

1
className={["title", index === this.state.active?"active":null].join(' ')}

  

方法三:classnames(需要下载classnames)

1
2
3
4
5
6
7
8
9
10
11
12
13
var classNames = require('classnames');
 
var Button = React.createClass({
  // ...
  render () {
    var btnClass = classNames({
      btn: true,
      'btn-pressed': this.state.isPressed,
      'btn-over': !this.state.isPressed && this.state.isHovered
    });
    return <button className={btnClass}>{this.props.label}</button>;
  }
});

  

posted @   明明一颗大白菜  阅读(18503)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
<-- -->
点击右上角即可分享
微信分享提示