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

时间:2020-05-08 22:46:54

标签: javascript css reactjs event-handling

朋友,我将一个eventHandler添加到div中,该监听器在用户滚动隐藏导航栏时侦听。由于执行滚动功能的容器是主体,因此效果很好,但是如果我将overflow:滚动样式添加到包含我的节的div中,则eventHandler将不再起作用。如何将相同的代码添加到包含.layoutContainer类的div中?

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

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

1 个答案:

答案 0 :(得分: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

执行