【问题标题】:Target another styled component on hover在悬停时定位另一个样式组件
【发布时间】:2017-04-21 18:46:54
【问题描述】:

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

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

【问题讨论】:

标签: reactjs styled-components


【解决方案1】:

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

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

更多信息请见the documentation

组件的顺序很重要。仅当ButtonWrapper 之前/之前定义时才有效。


如果您使用的是 v1 并且需要这样做,您可以使用自定义类名来解决它:

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

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

由于 v2 是 v1 的直接升级,我建议进行更新,但如果这不在卡片中,这是一个很好的解决方法。

【讨论】:

  • 对于任何阅读本文的人来说,组件的顺序很重要。只有在Button 上面/Wrapper@ 之前定义它才会起作用
  • 其实另一个重要的文档是Referring to other components
  • 如果我想依靠一些从 Wrapper 传递给 Button 的道具,那么悬停看起来会根据这些道具而有所不同?
  • 如果你想定位一个非子类组件怎么办。我的意思是他们有相同的级别元素
  • 有人在这里遇到打字稿和棉绒问题吗?我正在使用@emotion/styled,但我认为我遗漏了一些东西
【解决方案2】:

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

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

我无法告诉您何时引入此功能,但从 v3 开始就可以使用。

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

【讨论】:

  • 最新解决方案。
【解决方案3】:

我的解决办法是

const Content = styled.div`
  &:hover + ${ImgPortal} {
    &:after {
      opacity: 1;
    }
  }
`;

【讨论】:

    【解决方案4】:

    这个解决方案对我有用:

    const ContentB = styled.span`
      opacity: 0;
    
      &:hover {
        opacity: 1;
      }
    `
    
    const ContentA = styled.span`
      &:hover ~ ${ContentB} {
        opacity: 1;
      }
    `
    

    【讨论】:

      【解决方案5】:

      这对我有用

      const NoHoverLine = styled.div`
        a {
          &:hover {
            text-decoration: none;
          }
        }
      `
      

      【讨论】:

      • 请解释您的代码是如何工作的以及它是如何工作的。
      【解决方案6】:
      const ConnectButton = styled(WalletDialogButton)`
        background-color: #105b72;
        border: none;
        margin: 10vh auto;
        width: 250px;
      
        &:hover {
          background-color: #105b72c2;
        }
        `;
      

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

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

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 2020-02-06
        • 2021-04-08
        • 2017-09-16
        • 2011-10-21
        • 2016-07-07
        • 1970-01-01
        • 2017-12-30
        • 2018-05-18
        相关资源
        最近更新 更多