You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript中如何为滚动处理函数的事件添加类型?

解决TypeScript滚动事件中EventTarget无documentElement属性的类型错误

问题场景

页面实现懒加载功能,为document绑定滚动监听器后,scrollHandler函数将事件参数类型从any改为Event时触发以下错误:

TS2339: Property 'documentElement' does not exist on type 'EventTarget'.

原代码:

const scrollHandler = (e: any) => {
        let scrollHeight = e.target.documentElement.scrollHeight;
        let scrollTop = e.target.documentElement.scrollTop;
        let innerHeight = window.innerHeight;
        if (scrollHeight - (scrollTop + innerHeight) < 100) {
            dispatch(setStatus(Status.LOADING));
        }
    };

    useEffect(() => {
        document.addEventListener('scroll', scrollHandler);
        return function () {
            document.removeEventListener('scroll', scrollHandler);
        }
    });

解决方案

方案一:类型断言指定EventTarget为Document

将事件对象的target断言为Document类型,明确其拥有documentElement属性:

const scrollHandler = (e: Event) => {
    const target = e.target as Document;
    const scrollHeight = target.documentElement.scrollHeight;
    const scrollTop = target.documentElement.scrollTop;
    const innerHeight = window.innerHeight;
    
    if (scrollHeight - (scrollTop + innerHeight) < 100) {
        dispatch(setStatus(Status.LOADING));
    }
};

useEffect(() => {
    document.addEventListener('scroll', scrollHandler);
    return () => {
        document.removeEventListener('scroll', scrollHandler);
    };
}, []); // 空依赖数组避免重复绑定监听

方案二:直接访问document(更稳妥)

由于监听的是document的滚动事件,无需通过事件对象的target获取,直接使用document.documentElement即可,完全规避类型问题:

const scrollHandler = () => {
    const scrollHeight = document.documentElement.scrollHeight;
    const scrollTop = document.documentElement.scrollTop;
    const innerHeight = window.innerHeight;
    
    if (scrollHeight - (scrollTop + innerHeight) < 100) {
        dispatch(setStatus(Status.LOADING));
    }
};

useEffect(() => {
    document.addEventListener('scroll', scrollHandler);
    return () => {
        document.removeEventListener('scroll', scrollHandler);
    };
}, []);

内容的提问来源于stack exchange,提问作者Starkov Ivan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 17:20:32