【问题标题】:Target another styled component on hover not working悬停时定位另一个样式的组件不起作用
【发布时间】:2022-01-14 05:54:45
【问题描述】:

在样式化组件中悬停时需要帮助。如果悬停在组件中并影响该组件,则该组件有效。但是如果悬停在组件中并影响另一个组件,则无法正常工作。

DropDownContent 不显示在 DropDownLi:hover 上。

export const DropDownLi = styled(StyledLi)`
  display: inline-block;

  &:hover {
    color: red;
  }
`;

export const DropDownContent = styled.div`
  display: none;
  position: absolute;
  min-width: 160px;
  z-index: 1;

  ${DropDownLi}:hover & {
    display: block;
  } 
  /* not show on hover */
`;

在下一个示例中不起作用。

export const DropDownLi = styled(StyledLi)`
  display: inline-block;

  &:hover ${DropDownContent} {
    color: red;
  }
`;
<StyledUl>
  <DropDownLi>$ Currency</DropDownLi> 
  <DropDownContent>dvsdv</DropDownContent>
  <DropDownLi>English</DropDownLi>
  <StyledLi>Login</StyledLi>
</StyledUl>

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    尝试删除&amp;

    export const DropDownContent = styled.div`
      display: none;
      position: absolute;
      min-width: 160px;
      z-index: 1;
    
      ${DropDownLi}:hover {
        display: block;
      } 
      /* not show on hover */
    `;
    

    【讨论】:

    • 感谢@Georgy 的帮助,但如果没有&amp;,它将无法正常工作。
    • 啊,我明白了,如果您将鼠标悬停在子组件上,您想显示父组件,对吧?我不确定你是否可以使用 CSS 来做到这一点。级联工作从顶层到底层。
    • 我更新了问题,所以你可以看到。我想在悬停另一个子组件 (DropDownLi) 时显示子组件 (DropDownContent)。我需要带有样式组件的下拉菜单。谢谢你的帮助。
    【解决方案2】:

    我找到了解决这个问题的方法。有效的代码如下。

    <StyledUl>
      <DropDownLi>
        $ Currency
        <DropDownContent>dvsdv</DropDownContent>
      </DropDownLi>
    </StyledUl>
    
    export const StyledLi = styled.li`
      float: left;
      cursor: pointer;
    `;
    
    export const DropDownContent = styled.div`
      display: none;
      position: absolute;
      min-width: 160px;
      z-index: 1;
    `;
    export const DropDownLi = styled(StyledLi)`
      display: inline-block;
    `;
    
    export const StyledUl = styled.ul`
      list-style-type: none;
      margin: 0;
      overflow: hidden;
      color: black;
    
      ${DropDownLi}:hover > ${DropDownContent} {
        display: block;
      }
    `;
    

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 2020-02-06
      • 2021-10-28
      • 1970-01-01
      • 2017-09-16
      • 2019-05-18
      • 2021-04-08
      • 2021-07-13
      • 2011-03-07
      相关资源
      最近更新 更多