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

TypeScript错误:类型'never'不存在属性'contains'求助

解决React TypeScript中useRef类型错误问题

错误原因

你遇到的文件标红问题,核心是useRef未指定正确的DOM元素类型。TypeScript默认推断dropdownRef.current为null,而null不存在contains方法,调用时直接触发类型不匹配错误。

解决方案

给useRef指定对应DOM元素的类型(结合null适配初始值),同时明确MouseEvent的具体类型,修正后的代码如下:

import { useRef, useState } from 'react';

// 给buttonRef也指定对应DOM类型(假设是按钮元素)
const buttonRef = useRef<HTMLButtonElement | null>(null);
// 根据下拉菜单实际元素类型调整,比如ul用HTMLUListElement,div用HTMLDivElement
const dropdownRef = useRef<HTMLDivElement | null>(null);

const [dropHide, setDropHide] = useState({
  ishidden: true,
  icon: "line-md:chevron-small-right"
});

const closeOpenMenus = (e: MouseEvent<HTMLElement>) => {
  console.log(dropdownRef.current);
  // 用可选链简化空值判断,自动处理current为null的情况
  if (dropdownRef.current?.contains(e.target) === false && e.target !== buttonRef.current) {
    setDropHide({
      ishidden: true,
      icon: "line-md:chevron-small-right"
    });
  }
};

关键说明

  • 指定useRef泛型:根据下拉菜单的实际DOM元素选择对应HTML类型(如HTMLDivElement),加上| null适配初始值null,让TypeScript明确current的合法类型范围。
  • 可选链优化判断:dropdownRef.current?.contains会自动跳过current为null的情况,既简化代码,又消除类型错误。
  • 明确MouseEvent类型:给MouseEvent添加HTMLElement泛型,让e.target的类型更清晰,避免潜在的类型歧义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:20:03