classnames 是一个常用的 JavaScript 工具库,用于 安全、灵活地拼接 CSS 类名字符串 。
类名拼接
index.jsx
javascript
import classNames from 'classnames';
import styles from './index.less';
const LoginSubmit = ({ className, ...rest }) => {
const clsString = classNames(styles.submit, className);
...
};
这里做了两件事:
- 合并默认类名和自定义类名 :
- styles.submit :组件自身的默认样式类(来自 index.less 第 49-54 行)
- className :父组件传递进来的自定义类名(可能是 undefined 或 null )
- 安全处理空值 :
- 如果父组件没有传 className , classNames 会自动忽略它,不会在最终字符串中留下空格或 undefined
- 这比手动字符串拼接更安全: {styles.submit} {className || ''} 这样的写法可能会产生多余的空格
条件类名
index.jsx
javascript
const itemCls = classNames(styles.item, {
[styles.read]: item.read,
});
理解:
- 当 item.read 为 true 时 → 添加 styles.read 类
- 当 item.read 为 false 或 undefined 时 → 不添加这个类
这种写法非常适合处理 UI 状态(如:已读/未读、激活/禁用等)的样式切换!