Respect useRef 훅을 타이프 스크립트와 함께 사용하는 방법
새로운 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} >표시된 것과 같은 형제자매입니다. 레퍼런스는 소품으로 전달되는 시점에서는 사용할 준비가 되지 않습니다.이 경우 마운트에서 컴포넌트를 다시 렌더링해야 합니다.
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회피책으로는 더 나은 방법으로 할 수 있다고 생각됩니다.여기서의 실제적인 문제는 이다.PopoverRefact에서는 refs를 받아들이는 것이 일반적이지만 요소를 소품으로 받아들입니다.
현시점에서는 ref 오브젝트는 이점이 없습니다.Ref 콜백은 다음과 같이 사용할 수 있습니다.useState대신 state update 함수는 인수로서 새로운 상태를 수신하는 콜백이며, 같은 상태(DOM 요소)를 수신해도 추가 갱신은 발생하지 않습니다.
const [anchorEl, setAnchorEl] = useState<HTMLDivElement>(null);
...
{ anchorEl && <Popover
id="simple-popper"
open={open}
anchorEl={anchorEl}
...
}
<div ref={setAnchorEl} >
사용할 수 있습니다.MutableRefObject'timeout'에서 타이핑하다
import { MutableRefObject } from "react"
const anchorEl: MutableRefObject<HTMLDivElement> = React.useRef(null);
언급URL : https://stackoverflow.com/questions/54420778/how-to-use-react-useref-hook-with-typescript
'programing' 카테고리의 다른 글
| React는 상태 업데이트 순서를 유지합니까? (0) | 2023.03.01 |
|---|---|
| 기본 생성자가 있더라도 개체 값(위임자 또는 속성 기반 생성자 없음)에서 직렬을 해제할 수 없습니다. (0) | 2023.03.01 |
| WooCommerce REST API에서 "리소스를 나열할 수 없습니다" 오류가 발생했습니다. (0) | 2023.03.01 |
| 로컬 json 파일에 데이터를 쓸 수 있는 것은 angular만 있으면 됩니다. (0) | 2023.03.01 |
| 송신 후 검증 에러가 발생했을 경우, p:dialog를 열어 둡니다. (0) | 2023.03.01 |