簡體   English   中英

使用樣式組件在父級的 hover state 上隱藏子組件

[英]Hiding child component on hover state of parent using styled-component

我有一個像這樣的反應組件 -

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

我只想在用戶將鼠標懸停在ContainerSection上時顯示DeleteButtonContainer 它們都是styled-components I couldn't find any way to do it using just css (using hover state of parent inside child), so I used something like this using state -

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 ,因為它沒有 hover。 我知道我總是可以糾正更多的 JS 來實現這一點,但我想使用 CSS 來做到這一點,如果可能的話,我想完全刪除 state。

那么有沒有辦法只使用樣式化的組件而不是編寫自定義 JS 來實現這一點?

您可以在另一個組件中引用一個組件,並使用媒體查詢來啟用非移動分辨率的規則。

Hover 金色條看到按鈕,並縮小寬度以禁用 hover 規則。

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM