React 设置className数组,多个类名

news/2024/7/15 19:18:44 标签: react.js, 前端, javascript

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

比如说有一个固定样式"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 模板字符串 ``

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

方法二:join("")

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

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

const classNames = require('classnames');
 
const Button = React.createClass({
  // ...
  render () {
    const 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>;
  }
});

http://www.niftyadmin.cn/n/1162293.html

相关文章

SpringCloud 分布式配置Config Git

个人学习SpringCloud系列 分布式配置Config Git篇 Github Link: https://github.com/panjianlong13/SpringBoot-SpringCloud/tree/master/spring-cloud-config-git 随着线上项目变的日益庞大&#xff0c;每个项目都散落着各种配置文件&#xff0c;如果采用分布式的开发模式&am…

设置了alias以后vscode 点击路径跳转不了,也没有了智能提示路径,也找不到文件引用(Find file references)

设置了alias以后vscode 点击路径跳转不了讲个找文件被哪个文件引用的快捷方法webpack设置快捷访问的别名alias引发问题 点击路径跳转不了&#xff0c;也没有了智能提示路径&#xff08;输入了“”后没有提示src文件下的目录&#xff09;讲个找文件被哪个文件引用的快捷方法 右…

SpringCloud 分布式配置中心服务化与高可用

个人学习SpringCloud系列 分布式配置中心服务化与高可用篇 Github Link: https://github.com/panjianlong13/SpringBoot-SpringCloud/tree/master/spring-cloud-config-eureka&#xff09; 代码大部分参考&#xff08;https://github.com/souyunku/SpringCloudExamples/tree/…

前端面试之 options 请求详解

概述 options 请求就是预检请求&#xff0c;可用于检测服务器允许的 http 方法。当发起跨域请求时&#xff0c;由于安全原因&#xff0c;触发一定条件时浏览器会在正式请求之前自动先发起 OPTIONS 请求&#xff0c;即 CORS 预检请求&#xff0c;服务器若接受该跨域请求&#x…

SpringCloud 服务网关Zuul

个人学习SpringCloud系列 Zuul篇 Github Link: https://github.com/panjianlong13/SpringBoot-SpringCloud/tree/master/spring-cloud-zuul Spring Cloud Zuul简介 外部的应用如何来访问内部各种各样的微服务呢&#xff1f;在微服务架构中&#xff0c;后端服务往往不直接开放…

SpringCloud Zuul网关Filter

个人学习SpringCloud系列 Zuul Filter篇 Github Link: https://github.com/panjianlong13/SpringBoot-SpringCloud/tree/master/spring-cloud-zuul-filter Zuul 核心简介 Zuul 除了转发&#xff0c;动态路由&#xff0c;负载均衡等功能外&#xff0c;还可以用来鉴权、流量转发…

SpringCloud 分布式链路跟踪Sleuth 和 Zipkin

个人学习SpringCloud系列 Zipkin篇 Github Link: https://github.com/panjianlong13/SpringBoot-SpringCloud/tree/master/spring-cloud-sleuth-zipkin 随着业务发展&#xff0c;系统拆分导致系统调用链路愈发复杂一个前端请求可能最终需要调用很多次后端服务才能完成&#xf…

Spring 源码学习笔记(一) 整体架构

个人学习Spring源码系列 整体架构篇 源码地址 https://github.com/spring-projects/spring-framework Spring的整体架构 Spring是一个分层框架&#xff0c;它包含大约20个模块&#xff0c;如下图所示&#xff1a; Spring各模块简介 Data Access/Integration(数据访问集成) …