反应滚动事件

问题描述 投票:0回答:1

我试图显示滚动条仅在我通过反应滚动该区域时才会出现。 我使用 debounce 和 useState。

问题: 当我向下滚动到末尾时,滚动事件无限期地重复。 如果不向下滚动到底部,它看起来可以工作。

这是我的代码。

 const [isScroll, setIsScroll] = useState(false);

  const handleScroll = (e: any) => {
    console.log('Scroll Start');
    setIsScroll(true);
    handleScrollEnd();
  };

  const handleScrollEnd = useMemo(
    () =>
      debounce(() => {
        console.log('Scroll End');
        setIsScroll(false);
      }, 1000),
    [setIsScroll],
  );

  return (
    <div
      css={css`
        border: 1px solid;
        width: 500px;
        height: 200px;
        overflow: auto;
        display: flex;
        ${!isScroll && '::-webkit-scrollbar { display: none; }'}
      `}
      onScroll={handleScroll}
    >
      <div>
        Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece
        of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock,
        a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure
        Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the
        word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from
        sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and
        Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very
        popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit
        amet..", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since
        the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de
        Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form,
        accompanied by English versions from the 1914 translation by H. Rackham. Contrary to popular
        belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin
        literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor
        at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words...
      </div>
      <div
        css={css`
          width: 20px;
          flex-shrink: 0;
          flex-grow: 0;
        `}
      ></div>
    </div>

谢谢。

javascript reactjs typescript scroll debouncing
1个回答
0
投票

如果您想对该 div 的滚动事件执行某些操作,我可能会选择常规 JavaScript 事件侦听器。使用 useEffect 附加和清理侦听器并像在 vanilla JS 中一样处理事件。

© www.soinside.com 2019 - 2024. All rights reserved.