styled-components - 使用 emotion-js 在悬停时定位另一个组件

标签 styled-components emotion css-in-js

我知道这与 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;

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

最佳答案

这里有三个问题。

  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;

关于styled-components - 使用 emotion-js 在悬停时定位另一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58295923/

相关文章:

javascript - 样式化的组件输入失去对变化的关注

reactjs - React、Emotion 和 Jest 快照 : Error: property missing ':'

python - 微软情感API多图像PYTHON 2.7

reactjs - React-emotion 和外部 css(例如 bootstrap)类的组合

javascript - 从 JavaScript 设置 CSS 伪类规则

javascript - 情感风格组件中的媒体查询

javascript - 用对象声明的样式化组件中的媒体查询

css - 隐藏 span 标签不显示并显示内联

css - 按钮在 iOS 上的定位与 Windows 和 Android 上的不同