1 回答

TA貢獻1852條經驗 獲得超7個贊
您需要在 useEffect 回調函數中刪除監聽器:
useEffect(() => {
? const listener = () => {
? ? ?if (window.scrollY < (window.pageYOffset + divRef1.current.getBoundingClientRect().bottom)) {
? ? ? ? ?onHeaderColorSwitch('#c8e9e6')
? ? ? ? ?console.log('green')
? ? ?} else if (window.scrollY >= (window.pageYOffset + divRef2.current.getBoundingClientRect().top) &&? window.scrollY < (window.pageYOffset + divRef2.current.getBoundingClientRect().bottom)) {
? ? ? ? ?onHeaderColorSwitch('#ffae5a')
? ? ?} else if (window.scrollY >= (window.pageYOffset + divRef3.current.getBoundingClientRect().top) &&? window.scrollY < (window.pageYOffset + divRef3.current.getBoundingClientRect().bottom)) {
? ? ?}
? }
? document.addEventListener("scroll", listener);
? return () => {
? ? // Clean up the subscription
? ? document.removeEventListener(listener);
? };
}, []);
添加回答
舉報