こんにちは、userref に問題があります
const LandingPage = () => {
useEffect(() => {
document.addEventListener("scroll", () => {
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)) {
}
})
}, [])
}
私はこのコードを持っていますが、これを使用して連絡先ページに変更すると
function App() {
let routes =<Switch>
<Route path="/" exact component={landingPage}/>
<Route path="/contact" exact component={contactPage}/>
</Switch>
そして、新しいページをスクロールしようとすると、このエラーコードが表示されます
TypeError: Cannot read property 'getBoundingClientRect' of null
HTMLDocument.<anonymous>
my-app/src/screens/landingPage.js:22
19 |
20 | useEffect(() => {
21 | document.addEventListener("scroll", () => {
> 22 | if (window.scrollY < (window.pageYOffset + divRef1.current.getBoundingClientRect().bottom)) {
| ^ 23 | onHeaderColorSwitch('#c8e9e6')
24 |
25 | } else if (window.scrollY >= (window.pageYOffset + divRef2.current.getBoundingClientRect().top) && window.scrollY < (window.pageYOffset + divRef2.current.getBoundingClientRect().bottom)) {
新しいページに移動しても、イベント リスナーはまだリッスンしています。ページを更新すると、バグは影響しません。現在および将来、これを防ぐにはどうすればよいですか?