本文均以CSS modules做示范,配置在隔壁react 🀄️引入CSS modules🔗
安装包
npm install classnames
示例代码
import { useState } from "react";
import classNames from "classnames/bind"; // 注意需要引入.bind文件
import styles from "./index.css";
// 获得一个css的上下文环境
let cx = classNames.bind(styles);
export default function SubmitButton() {
const [count, setCount] = useState(1);
let className = cx({
// 右边可以写表达式,做条件判断,决定要不要加这个类名
success: count === 1,
warning: count === 2,
error: count === 3,
bg: count === 3,
});
const handleButton = () => {
setCount(count + 1);
if (count >= 3) setCount(1);
};
return (
<button className={className} onClick={handleButton}>
text
</button>
);
}
微改
import React, { useState } from "react";
import classNames from "classnames"; // 修改以后不需要引入.bind文件了
import styles from "./index.css";
export default function SubmitButton() {
const [count, setCount] = useState(1);
let className = classNames({
[styles.success]: count === 1,
[styles.warning]: count === 2,
[styles.error]: count === 3,
[styles.bg]: count === 3,
});
const handleButton = () => {
setCount(count + 1);
if (count >= 3) setCount(1);
};
return (
<>
<button className={className} onClick={handleButton}>
text
</button>
</>
);
}
其它用法
1.条件判断
import classNames from "classnames";
import { useState } from "react";
import styles from "./index.css";
export default function SubmitButton() {
const [bol, setBol] = useState(false);
const handleButton = () => {
setBol(!bol);
};
return (
<button
className={
bol ? classNames(styles.success) : classNames(styles.error, styles.bg)
}
onClick={handleButton}
>
text
</button>
);
}
2.变量做判断
className={classNames({ [`${styles.bg}`]: bol })}
其实平时不一定需要calssNames,也可以用条件判断
className={bol ? [styles.error, styles.bg].join(" ") : styles.success} //多类名
或则用枚举映射的方法
import React, { useState } from "react";
import styles from "./index.css";
export default function App() {
const [count, setCount] = useState(1);
const results = {
1: <tag className={styles.success}>准入</tag>,
2: <tag className={styles.warning}>待定</tag>,
3: <tag className={styles.error}>拒绝</tag>,
};
const handleButton = () => {
setCount(count + 1);
if (count >= 3) {
setCount(1);
}
};
return <div onClick={handleButton}>{results[count]}</div>;
}
不过需要注意这个改变的不仅仅是css,