我知道这与 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;
我希望当我将鼠标悬停在按钮上时显示链接,但这不起作用,我也不知道为什么
最佳答案
这里有三个问题。
您在定义
DropdownContent
之前引用它。重新排列您的代码,使DropdownContent
声明出现在使用它的标记模板文字之前,您应该可以开始了。生成的 css 选择器(类似于
button:hover .DropDownContent
)与您的 HTML 文档不匹配,其中DropDownContent
是Button 的兄弟
。您在
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/