【问题标题】:Event listener on className element, React JsclassName 元素上的事件侦听器,React Js
【发布时间】:2020-05-09 07:37:16
【问题描述】:

朋友们怎么样,我在 div 中添加了一个 eventHandler,它会在用户滚动隐藏导航栏时进行监听。它工作正常,因为执行滚动功能的容器是主体,但是如果我将溢出:滚动样式添加到包含我的部分的 div,则 eventHandler 不再起作用。如何将相同的代码添加到包含 .layoutContainer 类的 div 中?

  useEffect(() => {
    window.addEventListener("scroll", handleScroll, { passive: true });
    window.addEventListener("touchmove", handleScroll, {
      passive: true,
    });
  }, []);

我尝试做 getElementByClassName 但它不起作用。希望你能帮帮我,谢谢

【问题讨论】:

    标签: javascript css reactjs event-handling


    【解决方案1】:

    像这样?

    // see https://stackoverflow.com/questions/35939886/find-first-scrollable-parent
    function getScrollContainer(node) {
      while (node) {
        if (node.scrollHeight > node.clientHeight) {
          return node;
        }
        node = node.parentNode;
      }
      return null;
    }
    
    // we want a reference to the current DOM node
    const ref = React.useRef(null);
    
    useEffect(() => {
      // determine what element is scrolling
      const container = getScrollContainer(ref.current);
      if(!container) return;
    
      // add the event listener
      container.addEventListener("scroll", handleScroll, { passive: true });
      container.addEventListener("touchmove", handleScroll, { passive: true });
    
      return () => {
        // and clean up after yourself
        container.removeEventListener("scroll", handleScroll);
        container.removeEventListener("touchmove", handleScroll);
      }
    }, [/* sure that this doesn't rely on some dependency, like some `isVisible` state? */]);
    
    // set the ref so we get access to the DOM node
    return <div ref={ref} ...
    

    除非这个组件被添加,然后在handleScroll 上被删除,我几乎可以肯定你的效果应该基于一些依赖值来执行,而不仅仅是componentDidMount

    【讨论】:

    • 是的,谢谢你确定我让它工作,然后看到你的回复,这和我做的一样,只需要使用参考。非常感谢
    • @JoangelDeLaRosa,别忘了移除事件监听器。
    猜你喜欢
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    相关资源
    最近更新 更多