首页 > 解决方案 > useRef Typescript 错误:“HTMLElement”类型上不存在属性“当前”

问题描述

我正在用 React 和 Typescript 制作一个 Datepicker,我似乎无法克服useRefref.current属性的错误。当在文档之外单击文档时,我试图让div我分配的 ref 关闭。

我只是似乎无法弄清楚我做错了什么。这是我的代码:

function Datepicker({label, placeholder}: DatepickerProps){
  const [open, setOpen] = React.useState(false)
  const [day, setDay] = React.useState(0)
  const [month, setMonth] = React.useState(new Date().getMonth())
  const [year, setYear] = React.useState(new Date().getFullYear())
  const picker = React.useRef(null) as HTMLElement | null

  React.useEffect(() => {
    document.addEventListener("mousedown", toggle)
    return () => {
      document.removeEventListener("mousedown", toggle)
    };
  }, []);

  const toggle = (e: MouseEvent) => {
    if (picker && picker.current){
      if (picker.current.contains(e.target) === false){
        setOpen(false)
      }
    }
  }

  //...

  return(
    
    //...

    <div 
      ref={picker}
      className={"datepicker-picker" + (open ? " open" : "")}
    >

      //...

  )
}


React.useRef(null) as HTMLElement | null给我以下问题:

Conversion of type 'MutableRefObject<null>' to type 'HTMLElement' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type 'MutableRefObject<null>' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 234 more.ts(2352)

.current正在给我以下内容:

Property 'current' does not exist on type 'HTMLElement'.

当我尝试将 ref 应用于div元素时,它会显示以下内容:

Type 'HTMLElement | null' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
  Type 'HTMLElement' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
    Type 'HTMLElement' is not assignable to type 'string'.ts(2322)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

我正在使用 VSCode 作为我的 IDE,如果这有帮助的话。

标签: javascriptreactjstypescriptvisual-studio-codereact-hooks

解决方案


useRef不返回 ref 中的值 - 键入返回值HTMLElement | null不准确。请改用通用参数:

const picker = React.useRef<HTMLElement>(null);

您还需要进行更改toggle,以便根据需要进行类型缩小:

const toggle = (e: MouseEvent) => {
  const { current } = picker;
  if (current && !current.contains(e.target)) {
    setOpen(false);
  }
}

推荐阅读