【问题标题】:Ampersand Sass selector doesn't work with sibling selector in styled componentsAmpersand Sass 选择器不适用于样式化组件中的同级选择器
【发布时间】:2021-06-11 22:44:45
【问题描述】:
import styled from "styled-components";

const Styles = styled.div`
  .App {
    &__input {
      width: 200px;
      background-color: orangered;
      &:focus {
        background-color: greenyellow;
      }
    }
    &__button {
      background-color: grey;
    }
    /* this works */
    &__input:focus + .App__button {
      background-color: greenyellow;
    }

    /* this doesn't */
    &__input:focus + &__button {
      background-color: greenyellow;
    }
  }
`;

export default function App() {
  return (
    <Styles>
      <div className="App">
        <input className="App__input" />
        <button className="App__button">click</button>
      </div>
    </Styles>
  );
}

正如您在代码中看到的,我希望 &amp; 引用 .App,因为它在其他地方以及 node_sass 中都可以使用。

这是样式组件中的错误还是我在这里遗漏了什么?

这里是 codesandbox link 来复制问题。

【问题讨论】:

    标签: css sass styled-components


    【解决方案1】:

    也许问题出在这里:

    因为父选择器可以替换为 h1 之类的类型选择器,所以它只允许在复合选择器的开头,其中类型选择器也可以使用...

    它还说:

    它还可以用于在特定上下文中设置外部选择器的样式...

    在您的情况下,这似乎不是一个合适的“上下文”。

    请参阅 SASS 父选择器文档。 here.

    编辑

    当我们在不同于styled-components 的多个上下文中对其进行测试时,它确实有效,第一个选项得到了确认:

    这是styled-components 中的一个错误。

    【讨论】:

    • 我上面写的代码在 node-sass 包中运行良好。我只是在使用样式组件时遇到这个问题。如果你写 ``` .search{ &__input:focus + &__button { background-color: blue; } } ``` 在sassmeister.com
    • 好吧,我也试过在这里调整一些参数,再次,它按预期工作,然后它只是样式组件的一个错误。 (更新答案顺便说一句)。
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 2021-02-16
    • 2011-07-28
    • 1970-01-01
    • 2021-03-14
    • 2020-04-17
    • 2020-05-25
    • 1970-01-01
    相关资源
    最近更新 更多