How do I window removeEventListener using React useEffect

前端 未结 2 542
小蘑菇
小蘑菇 2021-01-01 11:03

In React Hooks documents it is shown how to removeEventListener during the component\'s cleanup phase. https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-

2条回答
  •  一整个雨季
    2021-01-01 11:14

    You can put the handleKeyUp function inside of the function given to useEffect and only add the listener and return a cleanup function when collapsed is false.

    useEffect(() => {
      if (!collapsed) {
        function handleKeyUp(event) {
          switch (event.key) {
            case "Escape":
              setCollapsed(true);
              break;
          }
        }
    
        window.addEventListener("keyup", handleKeyUp);
        return () => window.removeEventListener("keyup", handleKeyUp);
      }
    }, [collapsed]);
    

提交回复
热议问题