【问题标题】:react I want console.log() to be displayed when I scroll to the bottom反应我希望在滚动到底部时显示 console.log()
【发布时间】:2021-02-24 04:13:06
【问题描述】:

我想在列表滚动到底部时显示 console.log()。
以下代码在滚动到列表底部时不显示 console.log()。
此外, const { scrollTop, scrollHeight, clientHeight } 将显示错误。
错误信息
类型“未定义”的属性“scrollTop”不存在。 ts(2339)
类型“未定义”的属性“滚动高度”不存在。 ts(2339)
类型“未定义”的属性“clientHeight”不存在。 ts(2339)

import React, { FunctionComponent, useState, useEffect, useRef } from 'react';
const Test: FunctionComponent = () => {
  const listInnerRef = useRef();

  const onScroll = () => {
    if (listInnerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = listInnerRef.current;
      if (scrollTop + clientHeight === scrollHeight) {
        // TO SOMETHING HERE
        console.log('Reached bottom');
      }
    }
  };

  return (
      <div className="list">
        <div className="list-inner" onScroll={onScroll} ref={listInnerRef}>
          <ul>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
            <li className="height-100">aaaaaaaa</li>
          </ul>
        </div>
      </div>
  );
};

export default Test;

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:
    1. 您可以从总可滚动高度中减去滚动高度。
    2. 如果这等于可见区域,则您位于底部element.scrollHeight - element.scrollTop === element.clientHeight
    3. 在 react 中,只需为可滚动元素添加一个 onScroll 侦听器,并在回调中使用event.target
    函数句柄滚动(事件){ 变种节点=事件.目标; 常量底部 = node.scrollHeight - node.scrollTop === node.clientHeight; 如果(底部){ console.log('BOTTOM REACHED:', 底部); } }

    【讨论】:

    • 我在哪里调用上述过程?我可以摆脱onScroll进程吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2022-08-17
    相关资源
    最近更新 更多