我有一个类似的反应组件-
const MyComponent = () => (
<ContainerSection>
<DeleteButtonContainer>
<Button
theme="plain"
autoWidth
onClick={() => {
onDeleteClick();
}}
>
Delete
</Button>
</DeleteButtonContainer>
</ContainerSection>
);
我只想在用户将鼠标悬停在DeleteButtonContainer
上时显示ContainerSection
。他们两个都是styled-components
。我找不到仅使用CSS的方法(使用子代中父级的悬停状态),所以我使用了这样的状态-
const MyComponent = ()=>{
const [isHoveredState, setHoveredState] = useState<boolean>(false);
return (<ContainerSection onMouseEnter={() => setHoveredState(true)} onMouseLeave={() => setHoveredState(false)}>
<DeleteButtonContainer style={{ display: isHoveredState ? 'block' : 'none' }}>
<Button
theme="plain"
autoWidth
disabled={!isHoveredState}
onClick={() => {
onDeleteClick();
}}
>
Delete
</Button>
</DeleteButtonContainer>
</ContainerSection>)
};
现在,我要在移动设备上始终显示DeleteButtonContainer
,因为它没有悬停。我知道我总是可以使用更多的JS来实现这一点,但是我想使用CSS来做到这一点,如果可能的话,我想完全删除状态。
有没有办法仅使用样式化的组件而不编写自定义JS来实现这一目标?
答案 0 :(得分:2)
您可以在另一个组件中引用一个组件,并使用媒体查询为非移动分辨率启用规则。
将鼠标悬停在金条上以查看按钮,并缩小宽度以禁用悬停规则。
const DeleteButtonContainer = styled.div``;
const ContainerSection = styled.div`
height: 2em;
background: gold;
@media (min-width: 640px) { // when resolution is above 640px
&:not(:hover) ${DeleteButtonContainer} { // if DeleteButtonContainer is not under an hovered ContainerSection
display: none;
}
}
`;
const Button = styled.button``;
const MyComponent = () => (
<ContainerSection>
<DeleteButtonContainer>
<Button>
Delete
</Button>
</DeleteButtonContainer>
</ContainerSection>
);
ReactDOM.render(
<MyComponent />,
root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.4.0/styled-components.js"></script>
<div id="root"></div>