1 回答

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
您需要在 useEffect 回調(diào)函數(shù)中刪除監(jiān)聽器:
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);
? };
}, []);
添加回答
舉報(bào)