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

TypeScript中useInView的ref类型指定报错,求解决方案

解决TypeScript中react-intersection-observer useInView的类型不匹配问题

报错原因是useInView默认返回的ref类型为(node?: Element | null) => void,而<div>的ref期望的是LegacyRef<HTMLDivElement>类型,两者类型不兼容导致报错。

直接给useInView指定HTMLDivElement泛型,明确ref关联的元素类型即可解决:

import React from "react";
import { useInView } from "react-intersection-observer";

type PhotoProps = {
    name: string;
    imgUrl: string;
};

export default function Photo({ name, imgUrl }: PhotoProps) {
    // 指定泛型HTMLDivElement,让ref类型匹配div元素要求
    const { ref, inView } = useInView<HTMLDivElement>({
        threshold: 0.5,
    });

    return (
        <div ref={ref} className="photo--card">
            {inView ? <img src={imgUrl} alt={name} /> : <div className="Skeleton"></div>}
            <h4>{name}</h4>
        </div>
    );
}

你之前尝试指定ref类型失效,是因为没找对正确的泛型位置——不需要单独解构或手动修改ref类型,直接在useInView后添加<HTMLDivElement>就能让ref自动匹配<div>所需的类型,同时正常触发交叉观察逻辑。

内容的提问来源于stack exchange,提问作者proxor X7 Gh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 03:22:05