简体   繁体   中英

Not getting expected parameter on a function from an eventlistner callback

I am using a functional react component in which I am trying to add events to a couple of elements altogether. However I am not able to pass a trigger element to a function

export default function Header() {
    const background = document.querySelector('.dropdownBackground');
    const nav = document.querySelector('.top');

    useEffect(() => {
        let triggers = document.querySelectorAll('.cool > li');
        console.log(triggers);
        triggers.forEach(trigger => {
            trigger.addEventListener('mouseenter', trigger => handleEnter(trigger));
        });
    });

    function handleEnter(trigger) {
        // not getting proper value or trigger here. 
        // I am getting a MouseEvent object instead of a HTML element
        trigger.classList.add('trigger-active');
    }

    return (
        <nav className='header top w-100 justify-content-center'>
            <ul className='cool'>
                <li>
               {/* some HTML code */}
                </li>
            </ul>
        </nav>
    )
}

ADDENDUM: Updated the code to provide all required details.

Thanks!!

Change:

triggers.forEach(trigger => {
    trigger.addEventListener('mouseenter', trigger =>
handleEnter(trigger));
});

to:

triggers.forEach(trigger => {
    trigger.addEventListener('mouseenter', event => // can also use () instead of 'event', as you are not using it
handleEnter(trigger));
});

If you use (trigger) as a parameter in your arrow functions, you are naming trigger the MouseEvent , and passing it to the handlers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM