Appearance
BEM 辅助函数
沈孟平
最后更新于 2026-04-23 19:53:53
createBEM 用来快速生成符合 BEM 命名规范的 class 名,组件库内部很多组件都依赖它来统一 class 结构。
导出
| 名称 | 说明 |
|---|---|
createBEM | 创建一个 BEM class 生成器 |
BEM | createBEM 返回函数的类型 |
Mod / Mods | 修饰符相关类型 |
基础用法
ts
const bem = createBEM('button')
bem()
// 'button'
bem('text')
// 'button__text'
bem({ disabled: true })
// 'button button--disabled'
bem('text', { disabled: true })
// 'button__text button__text--disabled'
bem(['disabled', 'primary'])
// 'button button--disabled button--primary'参数说明
| 参数 | 类型 | 说明 |
|---|---|---|
name | string | BEM block 名称 |
el | string | Mods | 元素名;如果不是字符串,会被当成修饰符 |
mods | Mods | 修饰符,支持字符串、对象或数组 |
修饰符支持的形式
ts
bem('item', 'active')
// button__item button__item--active
bem('item', ['active', 'disabled'])
// button__item button__item--active button__item--disabled
bem('item', { active: true, disabled: false })
// button__item button__item--active适合的场景
- 组件内部 class 组合较多
- 既想保持 class 语义清晰,又不想手写字符串拼接
- 需要统一 block / element / modifier 命名规范