Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

reactjs - Target another styled component on hover

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 component and toggle a property on hover but was wondering if there is a better way to do this with styled-cmponents.

Something like the following doesn't work but would be ideal:

const Wrapper = styled.div`
  border-radius: 0.25rem;
  overflow: hidden;
  box-shadow: 0 3px 10px -3px rgba(0, 0, 0, 0.25);
  &:not(:last-child) {
    margin-bottom: 2rem;
  }
  &:hover {
    .button {
      display: none;
    }
  }
`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
  }
`

<Wrapper>
  <Button className="my__unique__button__class-asdf123" />
</Wrapper>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...