2016-12-06 36 views
21

在样式组件中处理悬停的最佳方法是什么?我有一个包装元素,当徘徊会揭示一个按钮。针对悬停的另一个样式的组件

我可以在组件上实现一些状态,并在悬停时切换属性,但想知道是否有更好的方式来使用样式化的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

这看起来很相关:https://github.com/styled-components/styled-components/issues/142 – nickspiel

回答

38

至于风格的组件V2的,可以估算出其他风格的成分是指其自动生成的类名。在你的情况,你可能会想要做这样的事情:

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

更多信息请参见the documentation


如果您使用v1和你需要做的这一点,你可以通过使用自定义类的名字解决它:

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

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

由于v2是一个简易升级从V1我D建议更新,但如果这不是卡片,这是一个很好的解决方法。

+3

对于阅读此内容的人来说,组件的顺序非常重要。只有在'包装器'之前定义'Button'时,它才会起作用 – Titan