123

处理样式组件中悬停的最佳方法是什么。我有一个包装元素,当悬停时会显示一个按钮。

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

6 回答 6

221

从 styled-components v2 开始,您可以插入其他样式组件以引用它们自动生成的类名。在你的情况下,你可能想要做这样的事情:

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

有关更多信息,请参阅文档

组件的顺序很重要。仅当Button在 above/before 定义时才有效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 的直接升级,我建议更新,但如果这不在卡片中,这是一个很好的解决方法。

于 2016-12-07T06:19:28.170 回答
49

与 mxstbr 的回答类似,您也可以使用插值来引用父组件。我喜欢这条路线,因为它比在父组件中引用子组件更好地封装了组件的样式。

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

我无法告诉您何时引入此功能,但这适用于 v3。

相关链接:https ://www.styled-components.com/docs/advanced#referring-to-other-components

于 2018-08-09T19:48:30.860 回答
5

我的解决方案是

const Content = styled.div`
  &:hover + ${ImgPortal} {
    &:after {
      opacity: 1;
    }
  }
`;
于 2018-08-31T07:59:26.500 回答
3

这对我有用

const NoHoverLine = styled.div`
  a {
    &:hover {
      text-decoration: none;
    }
  }
`
于 2020-12-09T21:51:30.410 回答
3
const ConnectButton = styled(WalletDialogButton)`
  background-color: #105b72;
  border: none;
  margin: 10vh auto;
  width: 250px;

  &:hover {
    background-color: #105b72c2;
  }
  `;

正如马科斯所说,这对我有用。我正在使用 styled() 而不是 styled.something

我真的不知道为什么,但我引用了一个WalletDialogButton存在的 node_modules 包。

于 2021-11-13T11:32:10.893 回答
0

这个解决方案对我有用:

const ContentB = styled.span`
  opacity: 0;

  &:hover {
    opacity: 1;
  }
`

const ContentA = styled.span`
  &:hover ~ ${ContentB} {
    opacity: 1;
  }
`
于 2020-10-14T23:28:30.013 回答