Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[React] 上拉加载更多 #171

Open
plh97 opened this issue Feb 15, 2021 · 0 comments
Open

[React] 上拉加载更多 #171

plh97 opened this issue Feb 15, 2021 · 0 comments
Assignees
Labels
react react项目

Comments

@plh97
Copy link
Owner

plh97 commented Feb 15, 2021

Screen.Recording.2023-04-24.at.3.27.20.AM.mov

这样处理的原因是因为, 当你滑到最顶部再 push 元素, 会直接定位到顶部, 需要scrollIntoView 到之前的位置.

export function ContentComponent() {
  const scrollEl = useRef<HTMLDivElement>(null);
  const [distanceToBottom, setDistanceToBottom] = useState<number | null>(null);
  // handle scroll event function, when scroll trigger it.
  const handleScroll = async () => {
    // when distance to top less than 300px
    if (
      message.length > 0 &&
      Number(scrollEl.current?.scrollTop) < 300 &&
      !loadingMessage &&
      hasMessage
    ) {
      // request API first
      const { payload } = await asyncLoadMessage();
      const distanceToTop = getTopSpace();
      dispatch(asyncLoadMessage(payload));
      // only when current position to top is 0px, need to reset scroll position
      if (Number(distanceToTop) === 0) {
        setDistanceToBottom(getBottomSpace());
      }
    }
  };

  useLayoutEffect(() => {
    if (
      scrollEl.current?.scrollTop !== undefined &&
      distanceToBottom !== null
    ) {
      scrollEl.current.scrollTop =
        scrollEl.current.scrollHeight - distanceToBottom;
      setDistanceToBottom(null);
    }
  }, [distanceToBottom]);

  return (
    <div
      className="overflow-y-auto flex-1 relative px-3.5 py-0"
      ref={scrollEl}
      onScroll={throttle(handleScroll)}
    >
      <TipComponent />
      {message.map((msg) => (
        <MessageComponent key={msg._id} data={msg} />
      ))}
    </div>
  )
}
@plh97 plh97 self-assigned this Feb 15, 2021
@plh97 plh97 added the react react项目 label Feb 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
react react项目
Projects
None yet
Development

No branches or pull requests

1 participant