参考文档
- https://www.npmjs.com/package/classnames
- https://github.com/JedWatson/classnames
安装
npm install classnames
示例
import classNames from "classnames";
// 字符串合并
console.log(classNames("foo", "bar")); // foo bar
// 对象合并
console.log(classNames({ foo: true, bar: false })); // foo
// 动态名称
let buttonType = "primary";
console.log(classNames({ [`btn-${buttonType}`]: true })); // btn-primary
Vue中的类名可以这么写
<div :class="{
'foo': true,
'bar': false
}">
React中可以借助classnames实现
App.css
.foo {
background-color: green;
}
.bar {
color: red;
}
App.jsx
import React from "react";
import classNames from "classnames";
import "./App.css";
export default function App() {
const boxClasses = classNames({
bar: true,
foo: true,
});
return <div className={boxClasses}>App</div>;
}
页面渲染的元素
<div class="bar foo">App</div>