【问题标题】:Styled components not applying styles样式化的组件不应用样式
【发布时间】:2021-01-12 13:51:45
【问题描述】:

我有这 2 个样式组件

  export const Icon = styled.svg`
  width: 8px;
  height: 8px;
  background: black;
`

export const Dots = styled.div`
  border: 2px solid green !imporant;
  height: 30px;
  background: white;
  width: 16px;
  height: 16px;
  border: solid 1px #d2d2d2;
  border-radius: 20px;
  top: 25px;
  position: relative;



  ${Icon}: hover {
    background:black;
  }
  
  }

`

我想在这个 div 的悬停上显示Icon,但我不明白为什么它不起作用, 请问有什么建议吗?

【问题讨论】:

  • 在上面的代码中hover被应用到Icon而不是div。
  • 我试过这样但没用&:hover { background-color: blue; ${Icon}; } @AntonBakinowsky

标签: reactjs styled-components


【解决方案1】:

您应该将悬停样式放在图标内

  export const Icon = styled.svg`
  width: 8px;
  height: 8px;
  background: black;

  &:hover {
    background: black;
  }

【讨论】:

    【解决方案2】:

    您的代码没有问题,除非在悬停时您不会从默认值更改颜色black

    const Icon = styled.div`
      width: 100px;
      height: 100px;
      background: black;
    `;
    
    export const Dots = styled.div`
      ${Icon}:hover {
        background: red;
      }
    `;
    
    export default function App() {
      return (
        <Dots>
          <Icon />
        </Dots>
      );
    }
    

    https://codesandbox.io/s/styled-react-template-forked-nzwm8

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2020-09-22
      • 2019-02-14
      • 2021-07-02
      • 2020-10-19
      相关资源
      最近更新 更多