【问题标题】:Target another component on hover using emotion-js使用emotion-js在悬停时定位另一个组件
【发布时间】:2020-02-06 07:20:15
【问题描述】:

我知道这与Target another styled component on hover非常相似

但是我想用emotion-js达到同样的效果

更具体地说,我正在尝试使用情感样式组件重新创建 this 示例

这是我的代码和我尝试过的。

import React from 'react';
import styled from '@emotion/styled';
import { Link } from 'gatsby';

const Dropdown = styled.div`
  postition: relative;
  display: inline-block;
`;

const Button = styled.div`
  background-color: green;
  color: white;
  &:hover {
    ${DropDownContent} {
      display: block;
    }
  }
`;

const DropDownContent = styled.div`
  display: none;
  position: absolute;
`;

const DropDownMenu = () => {
  return (
    <Dropdown>
      <Button>Dropdown</Button>
      <DropDownContent>
        <Link to="/">Link 1</Link>
      </DropDownContent>
    </Dropdown>
  );
};

export default DropDownMenu;

我希望在悬停按钮时显示链接,但这不起作用,我不知道为什么

【问题讨论】:

    标签: styled-components emotion css-in-js


    【解决方案1】:

    这里有三个问题。

    1. 您在定义之前引用了 DropdownContent。重新排列您的代码,使 DropdownContent 声明出现在使用它的标记模板文字之前,您应该一切顺利。

    2. 生成的 css 选择器(类似于 button:hover .DropDownContent)与您的 HTML 文档不匹配,其中 DropDownContentButton 的兄弟。

    3. Dropdown 上的 position 属性拼写错误。

    解决所有三个问题后,您的代码可能如下所示:

    import React from 'react';
    import styled from '@emotion/styled';
    import { Link } from 'gatsby';
    
    const Dropdown = styled.div`
      position: relative;
      display: inline-block;
    `;
    
    const DropDownContent = styled.div`
      display: none;
      position: absolute;
    `;
    
    const Button = styled.div`
      background-color: green;
      color: white;
      &:hover + ${DropDownContent} {
        display: block;
      }
    `;
    
    const DropDownMenu = () => {
      return (
        <Dropdown>
          <Button>Dropdown</Button>
          <DropDownContent>
            <Link to="/">Link 1</Link>
          </DropDownContent>
        </Dropdown>
      );
    };
    
    export default DropDownMenu;
    

    【讨论】:

    • 摆脱伪选择器 + 为我工作并更改我的降价以将 Button 包裹在 DropDownContent 周围。我认为这是有道理的,因为我们希望在将鼠标悬停在按钮和链接上时改变 DropDownContent 样式
    猜你喜欢
    • 2017-04-21
    • 2022-01-14
    • 1970-01-01
    • 2013-12-28
    • 2020-11-16
    • 1970-01-01
    • 2013-10-03
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多