简体   繁体   中英

window.removeEventListener in ReactJS doesn't work

Why when I click the button to close the sticky element, it becomes sticky again on scroll as if I didn't remove the scroll eventListener ?

export default function MyComponent(props) {
    const [sticky, setSticky] = useState(false)
    const [hidden, setHidden] = useState(false)

    const handler = () => {
        setSticky(window.scrollY > 700)
    }

    const closeSticky = () => {
        setHidden(true)
        window.removeEventListener("scroll", handler, false)
        setSticky(false)
    }

    useEffect(() => {
        if (hidden === false){
            window.addEventListener("scroll", handler, false)
        }
    }, [])

    return (
        ...

        <button onClick={() => {closeSticky()}} />
        <div className={styles.myDiv} style={sticky ? {display: 'block'} : {display: 'none'}}>
        etc...

Sandbox link: https://codesandbox.io/s/practical-fire-xk061?file=/src/App.js

I worked on your code and was able to solve the problem for you.

Also, your code was a bit cluttered and I cleaned it up a bit according to my personal taste

import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
  const [sticky, setSticky] = useState(true);
  const [hidden, setHidden] = useState(false);
  const handler = () => setSticky(hidden ? false > 700 : window.scrollY);
  const closeSticky = () => setSticky(false);
  useEffect(() => {
    if (sticky) {
      window.addEventListener("scroll", handler, false);
      setHidden(false);
    } else {
      window.removeEventListener("scroll", handler, false);
      setHidden(true);
    }
  }, [sticky]);
  return (<>
    <button onClick={() => closeSticky()}>&times;</button>
    <div className="myDiv" />
    {!hidden && window.scrollY > 700 ? <div className="myStickyDiv" /> : null}
  </>);
}

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