programing

Respect useRef 훅을 타이프 스크립트와 함께 사용하는 방법

newnotes 2023. 3. 1. 11:30
반응형

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

반응형