【问题标题】:Hiding child component on hover state of parent using styled-component使用样式化组件在父级悬停状态下隐藏子组件
【发布时间】:2019-10-28 20:25:51
【问题描述】:

我有一个这样的反应组件 -

const MyComponent = () => (
    <ContainerSection>
        <DeleteButtonContainer>
            <Button
                theme="plain"
                autoWidth
                onClick={() => {
                    onDeleteClick();
                }}
            >
                Delete
            </Button>
        </DeleteButtonContainer>
    </ContainerSection>
);

我只想在用户将鼠标悬停在ContainerSection 上时才显示DeleteButtonContainer。他们都是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 来实现这一点?

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    您可以在另一个组件中引用一个组件,并使用媒体查询来启用非移动分辨率的规则。

    悬停金色条以查看按钮,缩小宽度以禁用悬停规则。

    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>

    【讨论】:

    • 完美!这就是我需要的。谢谢:-)
    猜你喜欢
    • 2020-07-10
    • 1970-01-01
    • 2018-05-18
    • 2013-01-08
    • 1970-01-01
    • 2021-07-10
    • 2020-06-29
    • 1970-01-01
    • 2018-07-28
    相关资源
    最近更新 更多