[英]How to use useRef hook and getClientBoundingRect with React and 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.