了解样式化组件组件选择器和符号

Understanding styled components component selector and ampersand

在 styled-components 文档中,他们有这个例子:

https://www.styled-components.com/docs/advanced#referring-to-other-components

它显示了一个图标,当您悬停其父级时会改变颜色,在本例中为 link。

const Link = styled.a`
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background: papayawhip;
  color: palevioletred;
`;

const Icon = styled.svg`
  flex: none;
  transition: fill 0.25s;
  width: 48px;
  height: 48px;

  ${Link}:hover & {         // <---- This is what I'm not understanding
    fill: rebeccapurple;
  }
`;

从文档中,我们知道:

Doc Note #1: styled-components solves this use case cleanly via the "component selector" pattern. Whenever a component is created or wrapped by the styled() factory function, it is also assigned a stable CSS class for use in targeting.

还有:

Doc Note #2: Ampersands (&) get replaced by our generated, unique classname for that styled component, making it easy to have complex logic.


我们来分析一下${Link}:hover &

我知道它被翻译成浏览器:

和:

我知道 sc-kAzzGY 是 "stable CSS class"(文档注释 #1),每当元素被 styled 函数包装时创建。

我还知道,&符号 (&) 会被它们为该样式组件生成的唯一 class名称(文档注释 #2)所取代。因此,kDmLky 就是 class.

问题

但是生成的选择器(下图)实际上选择了什么?谁能给我解释一下?

${Link} 指向 const Link 即:"Hovering my parent changes my style" 得到 sc-kAzzGY 的 class。

& 有点像说“And 将其添加到当前的 class(es)/id(s)/etc”。 所以,

.my-class {
 some-css: awesomeness;
 &:hover {
   more-css: extra-cool;
 }
}

相当于:

.my-class {
 some-css: awesomeness;
}
.my-class:hover {
   more-css: extra-cool;
}

因此,& 指向包含元素 const Icon 即对话泡泡,并得到 kDmLky 的 class。

Link 悬停时,导致 Iconfill: rebeccapurple

编辑:

再澄清一下:

当您在另一个声明块内部有一个声明块时,如下例所示,该内部声明块将成为一个独立的声明块。

const Icon = styled.svg`
  flex: none;
  transition: fill 0.25s;
  width: 48px;
  height: 48px;

  ${Link}:hover & {       // This declaraition block becomes an independent one
    fill: rebeccapurple;
  }
`;

在这种情况下,结果是一个带有选择的声明块:

当您有一个 class & 是处于 hover 状态的 class ${Link} 的后代时,应用这些规则:

fill: rebeccapurple;

注意: ${Link} 指的是 Link class 而 & 指的是图标 class (svg).

${Link}:hover &

这里的 & 符号 & 是引用被定义的顶级组件的简写方式,因此我将其读作

${Link}:hover ${Icon}

即它指的是包含在悬停在

上的 Link 组件内的图标组件

我还建议 this link 查看带有样式组件的组件选择器的更一般用例,它在父子配置中用于选择,并应用于子组件