如何在React JS中使用window.addEventListener

我试图弄清楚如何在React中实现window.addEventListener。我正在用盖茨比开发一个网站,并且在“开发”环境中可以正常工作,但是每当我开始生产时都会出现错误。这是我的代码:

const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};

// Run the checkHeader function every time you scroll
window.addEventListener('scroll', checkHeader);

我想在滚动时应用一个类。我已经检查过我不能使用“窗口”。在React中在React中如何实现此代码?

评论
喵oo
喵oo

You can directly add window events with Gatsby since it performs server side rendering. To do that you need to add you listeners in gatsby-browser.js inside onClientEntry method which is called when client is loaded

// gatsby-browser.js
// ES6


const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};


export const onClientEntry = () => {
   // Run the checkHeader function every time you scroll
   window.addEventListener('scroll', checkHeader);
}
点赞
评论
哼~
哼~
const checkHeader = () => { 
    // Detect scroll position
    let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
    if (viewportWidth > 1100) {
        let scrollPosition = Math.round(window.scrollY);

        if (scrollPosition > 100){
            document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
        }
        else {
            document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
        }

    } else {

    }
};

// Run the checkHeader function every time you scroll
if (typeof window !== 'undefined') {
    window.addEventListener('scroll', checkHeader);
}
点赞
评论