在React中切换CSS类 [英] Toggle css class in React

查看:73
本文介绍了在React中切换CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用布尔值在React中的元素上切换CSS类的存在?在Angular 2中,我可以做 [class.red] ="isRed" .如何在React中做熟悉的事情?

How to toggle a presence of css class on element in React with boolean value? In Angular 2 I could just do [class.red]="isRed". How to do familiar thing in React?

推荐答案

在React中,元素使用这样的语法获取其类

In React, elements get their classes using a syntax like this

<div className="some-class" />

但是请注意,JSX允许属性值成为JS表达式

Note however that JSX allows attribute values to be JS expressions

<div className={"some-" + "class"} />

可用于根据某些逻辑(例如您的布尔检查)生成类名

Which can be used generate a class name based on some logic, such as your boolean check

<div className={isRed ? "red" : null} />

如果您的元素还应该具有一些不依赖变量的类,并且应始终应用,则可以使用

If your element should also has some classes that don't depend on a variable and should always be applied, this can be achieved with

<div className={"my-class " + (isRed ? "red" : null)} />

这时似乎开始变得混乱了,最好将其提取到局部变量中

At which point it seems to start to get messy and it's probably better to extract that into a local variable instead

var className = "my-class " + (isRed ? "red" : null);
<div className={className} />

React本身不提供实用程序功能来处理此问题,但是布尔模式非常普遍,有一个名为类名,将上面的内容变成

React itself doesn't provide an utility function to deal with this, however the boolean pattern is so common, there is a package called classnames that will turn the above into

var className = cx("my-class", { "red": isRed });
<div className={className} />

这篇关于在React中切换CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆