处理样式组件中悬停的最佳方法是什么。我有一个包裹元素,当悬停时会显示一个按钮。
我可以在组件上实现一些状态并在悬停时切换属性,但是想知道是否有更好的方法可以使用styled-cmponents。
以下内容不起作用但是理想:
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;
}
}
`
答案 0 :(得分:91)
从样式组件v2开始,您可以插入其他样式组件以引用其自动生成的类名。在你的情况下,你可能想要做这样的事情:
const Wrapper = styled.div`
&:hover ${Button} {
display: none;
}
`
有关详细信息,请参阅the documentation!
组件的顺序很重要。只有在Button
之前/之前定义Wrapper
时,它才有效。
如果你正在使用v1而你需要这样做,你可以使用自定义类名解决它:
const Wrapper = styled.div`
&:hover .my__unique__button__class-asdf123 {
display: none;
}
`
<Wrapper>
<Button className="my__unique__button__class-asdf123" />
</Wrapper>
由于v2是v1的直接升级,我建议更新,但如果不在卡中,这是一个很好的解决方法。
答案 1 :(得分:12)
类似于mxstbr的答案,您还可以使用插值来引用父组件。我喜欢这种方法,因为它封装了组件的样式比引用父组件中的子组件要好一些。
const Button = styled.button`
${Wrapper}:hover & {
display: none;
}
`;
我无法告诉您何时引入了此功能,但该功能自v3起有效。
相关链接:https://www.styled-components.com/docs/advanced#referring-to-other-components
答案 2 :(得分:1)
对我来说解决方案是...
const Content = styled.div`
&:hover + ${ImgPortal} {
&:after {
opacity: 1;
}
}
`;
答案 3 :(得分:0)
此解决方案对我有用:
const ContentB = styled.span`
opacity: 0;
&:hover {
opacity: 1;
}
`
const ContentA = styled.span`
&:hover ~ ${ContentB} {
opacity: 1;
}
`
答案 4 :(得分:0)
这对我有用
const NoHoverLine = styled.div`
a {
&:hover {
text-decoration: none;
}
}
`