繁体   English   中英

如何将 React useRef 钩子与 typescript 一起使用?

[英]How to use React useRef hook with typescript?

我正在使用新的 useRef 挂钩创建引用

const anchorEl = React.useRef<HTMLDivElement>(null)

并使用像

<div style={{ width: "15%", ...flexer, justifyContent: "flex-end" }}>
    <Popover
        id="simple-popper"
        open={open}
        anchorEl={anchorEl}
        onClose={() => {
          setOpen(false)
        }}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
    >
        <Typography>The content of the Popover.</Typography>
    </Popover>
</div>
<div ref={anchorEl} >
      ...

但我得到这个错误

TS2322: Type 'MutableRefObject<HTMLDivElement>' is not assignable to type 'HTMLElement | ((element: HTMLElement) => HTMLElement)'.
  Type 'MutableRefObject<HTMLDivElement>' is not assignable to type '(element: HTMLElement) => HTMLElement'.
    Type 'MutableRefObject<HTMLDivElement>' provides no match for the signature '(element: HTMLElement): HTMLElement'.
Version: typescript 3.2.2, tslint 5.12.0

anchorEl变量是 ref 对象,一个只有current属性的对象。 不知道Popover是如何工作的,但是它期望一个元素作为anchorEl道具,而不是参考。

它应该是:

<Popover
    id="simple-popper"
    open={open}
    anchorEl={anchorEl.current}

如果<Popover<div ref={anchorEl} >是兄弟姐妹,就像它显示的那样,当它作为 prop 传递时,ref 将无法使用。 在这种情况下,需要在挂载时重新渲染组件:

const [, forceUpdate] = useState(null);

useEffect(() => {
  forceUpdate({});
}, []);

...

   { anchorEl.current && <Popover
        id="simple-popper"
        open={open}
        anchorEl={anchorEl.current}
        ...
   }
   <div ref={anchorEl} >

如果<div ref={anchorEl} >不必渲染到 DOM,它可能是

   <Popover
        id="simple-popper"
        open={open}
        anchorEl={<div/>}

两次渲染组件并使用forceUpdate解决方法的必要性表明这可以以更好的方式完成。 这里的实际问题是Popover接受一个元素作为 prop,而接受 refs 在 React 中很常见。

此时 ref 对象没有任何好处。Ref 回调可以与useState一起使用,状态更新函数是接收新状态作为参数的回调,如果它接收到相同的状态(DOM 元素),则不会导致额外的更新:

const [anchorEl, setAnchorEl] = useState<HTMLDivElement>(null);

...

   { anchorEl && <Popover
        id="simple-popper"
        open={open}
        anchorEl={anchorEl}
        ...
   }
   <div ref={setAnchorEl} >

您可以使用“反应”中的MutableRefObject类型

import { MutableRefObject } from "react"

const anchorEl: MutableRefObject<HTMLDivElement> = React.useRef(null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM