【问题标题】:Issue with "M" in BEM with React CSS Module带有 React CSS 模块的 BEM 中的“M”问题
【发布时间】:2018-01-18 00:16:43
【问题描述】:

我正在尝试将 BEM 与我的项目结合起来。元素部分(block__element)很好,但是当我尝试命名修饰符(block__element--modifier)时一直出错。下面是我的代码,包括错误、我为 BEM 编写的 mixin、SCSS sn-p 以及我的 IDE (webstorm) 中的设置。我尝试了所有不同的东西(不使用 mixin 等),但似乎没有任何效果。请帮忙!

【问题讨论】:

  • 您不能在 javascript 标识符中使用 -,因为这将被解释为减法运算符。如果对象键的名称包含标识符的无效字符,则只能使用方括号访问它,例如 styles['card__content--icn']

标签: javascript reactjs sass classname bem


【解决方案1】:

你使用修饰符的方式完全不正确。

修饰符不是子元素,它们是块和元素的修饰符,没有母体就不能使用。

正确:

  • <div class="b">
  • <div class="b__e">
  • <div class="b b--m1 b--m2">
  • <div class="b__e b__e--m b__e--m2">

不正确:

  • <div class="b--m1">
  • <div class="b__e--m">

之所以会这样工作,是因为修饰符的本质——它们与接口或混入非常接近,它们不能在没有块的情况下使用,就像接口不能在没有类的情况下使用一样。

在此处阅读有关修饰符的更多信息:https://en.bem.info/methodology/key-concepts/#modifier

另一件事你不应该在你的 HTML 结构中重复 BEM 结构。

所以这是不正确的:

<div className={styles.card__content}>
    <div className={styles['card__content--icn']}>Icon</div>
    <div className={styles['card__content--sub']}>Test</div>
</div>

这是正确的:

<div className={styles.card__content}>
    <div className={styles.card__icon}>Icon</div>
    <div className={styles.card__sub}>Test</div>
</div>

https://en.bem.info/methodology/faq/#can-i-create-elements-of-elements-block__elem1__elem2


如果您对将 BEM 与 React 结合使用感兴趣,您应该看看 bem-react-core - 帮助您生成 BEM 类、提供运行时等的微型库:

【讨论】:

  • 你太棒了。我对 BEM 的理解非常有限。非常感谢!
  • 谢谢。 :-) 我很乐意提供帮助。
  • 如何组合多个类? &lt;button className={styles['button button--alert']}&gt;button&lt;/button&gt; 似乎不起作用..
  • 手动:className={[styles['button'], styles['button--alert']].join(' ')}
  • 神奇地:b('button').m('alert') 见:github.com/awinogradov/easy-bem-naminggithub.com/azproduction/b_
【解决方案2】:

您可以使用另一种对象形式的记录。试试这样的:className={styles['card_content--icn']}

【讨论】:

  • 太棒了。谢谢!你能解释一下为什么点符号不起作用吗?
  • 这是因为js引擎接受“-”作为数学减号,所以你必须将key作为字符串传递给object
猜你喜欢
  • 2019-05-23
  • 2019-05-14
  • 2017-03-26
  • 1970-01-01
  • 2018-05-23
  • 2019-03-09
  • 2020-02-22
  • 2019-02-28
相关资源
最近更新 更多