const [scrollY, setScrollY] = useState(0);
const handleScroll = () => {
//scrollY의 값을 현재 스크롤 값으로 변경
setScrollY(window.pageYOffset);
};
useEffect(() => {
const watch = () => {
window.addEventListener('scroll', handleScroll);
};
watch();
return () => {
window.removeEventListener('scroll', handleScroll);
};
});
//현재 스크롤 값
<NavBox scrollY={scrollY}>
//style
const NavBox = styled.nav`
display: flex;
align-items: center;
justify-content: space-between;
position: fixed;
height: 70px;
width: 100%;
z-index: 1; //nav를 맨 앞으로 가져오기(이미지가 맨 앞으로 나온 상태였음)
transition: 0.5s ease; //nav가 자연스럽게 변경
//현재 스크롤 값이 690 초과면 ? background-color를 변경 : 아니면 부모 색깔
${({ scrollY }) => {
return scrollY > 690
? 'background-color: #003300'
: 'background-color: transparent';
}}
const [scrollY, setScrollY] = useState(0);
const handleScroll = () => {
setScrollY(window.pageYOffset);
if (scrollY > 600) {
setScrollY(1);
}
};
useEffect(() => {
const watch = () => {
window.addEventListener('scroll', handleScroll);
};
watch();
return () => {
window.removeEventListener('scroll', handleScroll);
};
});
//style
const NavBox = styled.nav`
display: flex;
align-items: center;
justify-content: space-between;
position: fixed;
height: 70px;
width: 100%;
z-index: 9900;
${({ show }) => {
return show === 1 ? 'background-color: #003300' : '';
}}
`;
스크롤을 하면 배경색은 바뀌나 스크롤을 하는 도중 계속 깜빡거렸다.
렌더에 문제가 있는 줄 알고 throttle도 사용해보고 하루종일 이것 저것 바꿔봤지만 소용없었다.
그렇게 코드를 찬찬히 보던 중 스타일에서 false일 때 과연 빈공간이 맞을까라는 의문이 들면서 바꿔봤더니 해결됐다..
오늘도 깨닫는다 삽질은 나를 성장시킨다 ..