繁体   English   中英

className 元素上的事件侦听器,React Js

[英]Event listener on className element, React Js

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

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

我尝试做 getElementByClassName 但它没有用。 希望你能帮助我,谢谢

像这样?

// 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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