在悬停时定位另一个样式组件 [英] 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.
我可以在组件上实现一些状态并在悬停时切换一个属性,但想知道是否有更好的方法来使用 styled-cmcomponents 来做到这一点.
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;
}
}
`
推荐答案
从 styled-components v2 开始,您可以插入其他样式组件以引用它们自动生成的类名.在你的情况下,你可能想要做这样的事情:
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!
组件的顺序很重要.仅当 Button
在 Wrapper
之上/之前定义时,它才有效.
The order of components is important. It will only work if Button
is defined above/before Wrapper
.
如果您使用的是 v1 并且需要执行此操作,则可以使用自定义类名来解决此问题:
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>
由于 v2 是 v1 的直接升级,我建议更新,但如果这不在卡片中,这是一个很好的解决方法.
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.
这篇关于在悬停时定位另一个样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!