useEffect挂钩的第二个参数

时间:2020-03-29 22:16:29

标签: reactjs

有人可以告诉我为什么这样做吗? 当我向上滚动时,仅在useEffect的第二个参数为[true]时显示标题。 偶然造成的,给了我积极的结果。

向下滚动->隐藏标题

代码:

const StyledHeader = styled.header`
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100vw;
    height: 70px;
    padding: 5px 35px;
    position: ${({ showHeader }) => (showHeader ? 'fixed' : 'absolute')};
    top: 0;
    left: 0;
    right: 0;
    z-index: 9999;
    background-color: ${({ showHeader }) => (showHeader ? 'white' : 'none')};
`;

const StyledTestBottom = styled.div`
    position: fixed;
    bottom: 0;
    width: 100vw;
    background-color: red;
`;

const Header = () => {
    const [showHeader, setShowHeader] = useState(false);
    useEffect(() => {
        let scrollPos = 0;
        window.addEventListener('scroll', () => {
            if (document.body.getBoundingClientRect().top > scrollPos) {
                //scrolling up
                setShowHeader(true);
            } else {
                //scrolling down
                setShowHeader(false);
            }
            scrollPos = document.body.getBoundingClientRect().top;
        });
        //Second argument of useEffect  provides me to display header when scroll with direction 'up'
    }, [true]);

    return (
        <StyledHeader showHeader={showHeader}>
            <Logo />
            <Navigation />
            {showHeader && <StyledTestBottom />}
        </StyledHeader>
    );
};

0 个答案:

没有答案