本篇记录如何使用React中的classSet,为一个DOM节点指定多个不同的class。
如果我们要为一个DOM节点设置多个不同的class,一般是下面这种写法:
<input type="text" class="class1 class2 class3" />
在React中,如果不使用classSet,要为一个DOM节点指定多个不同的class,可能是下面这种写法:
var App = React.createClass({
render: function() {
var classString = "";
if(this.props.important) {
classString = "important";
}else{
classString = "normal";
}
return (
<p className={classString}>{this.props.text}</p>
);
}
});
在上面的代码中,通过important属性,来判断是否要给<p>标签添加名为important的class,其中important和normal的css样式如下:
<style type="text/css">
.important {
color: red;
}
.normal {
color: black;
}
</style>
上面这种写法虽然可以达到效果,但是当class多起来的时候,可能用起来就不是很方便了,所以React为我们提供了一种简单的操纵class属性的方式,即classSet。
关于classSet的用法,用下面的代码来说明:
var App2 = React.createClass({
render: function() {
var cx = React.addons.classSet;
var classes = cx({
"important": this.props.important == true,
"normal": this.props.important == false
});
return (
<p className={classes}>{this.props.text}</p>
);
}
});
classSet是React.addons中的一个对象,需要引入react-with-addons.js文件才可以使用,上面的代码中,classes返回的即包含了多个class属性的字符串,是否需要包含important或者normal,需要根据后面的表达式来确定,若表达式的值为true,则表示需要对应的class,若为false,则代表不需要对应的class,下面用一个demo记录classSet的用法,在浏览器中运行的结果如下图:
下面是代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>classSet用法</title>
<script type="text/javascript" src="../react-0.13.0/build/react-with-addons.js"></script>
<script type="text/javascript" src="../react-0.13.0/build/JSXTransformer.js"></script>
<style type="text/css">
.important {
color: red;
}
.normal {
color: black;
}
.bigText {
font-size: 40px;
}
</style>
</head>
<body>
<script type="text/jsx">
var App = React.createClass({
render: function() {
var classString = "";
if(this.props.important) {
classString = "important";
}else{
classString = "normal";
}
return (
<p className={classString}>{this.props.text}</p>
);
}
});
var App2 = React.createClass({
render: function() {
var cx = React.addons.classSet;
var classes = cx({
"important": this.props.important == true,
"normal": this.props.important == false
});
return (
<p className={classes}>{this.props.text}</p>
);
}
});
var App3 = React.createClass({
render: function() {
var cx = React.addons.classSet;
var classes = cx("bigText", "important");
return (
<p className={classes}>{this.props.text}</p>
);
}
});
React.render(
<div>
1. 为不同属性设置不同class的普通做法,用js代码判断是否需要添加class<br/>
<App important={false} text="this is not important string." />
<App important={true} text="this is important string." />
<hr/>
2. 为不同属性设置不同class的使用classSet的做法,classSet会根据表达式的值,自动设置class<br/>
<App2 important={false} text="this is not important string." />
<App2 important={true} text="this is important string." />
<hr/>
3. classSet使用多个class,将文本变大变红<br/>
<App3 text="Hello world!" />
</div>,
document.body
);
</script>
</body>
</html>