Target another styled component on hover

后端 未结 5 922
长情又很酷
长情又很酷 2020-12-12 11:42

What is the best way to handle hovers in styled-components. I have a wrapping element that when hovered will reveal a button.

I could implement some state on the com

5条回答
  •  悲&欢浪女
    2020-12-12 12:07

    As of styled-components v2 you can interpolate other styled components to refer to their automatically generated class names. In your case you'll probably want to do something like this:

    const Wrapper = styled.div`
      &:hover ${Button} {
        display: none;
      }
    `
    

    See the documentation for more information!

    The order of components is important. It will only work if Button is defined above/before Wrapper.


    If you're using v1 and you need to do this you can work around it by using a custom class name:

    const Wrapper = styled.div`
      &:hover .my__unique__button__class-asdf123 {
        display: none;
      }
    `
    
    
      

    Since v2 is a drop-in upgrade from v1 I'd recommend updating, but if that's not in the cards this is a fine workaround.

提交回复
热议问题