【问题标题】:How to use useRef hook and getClientBoundingRect with React and Typescript?如何在 React 和 Typescript 中使用 useRef 钩子和 getClientBoundingRect?
【发布时间】:2020-05-09 01:47:57
【问题描述】:

每个人。

我需要在 React 上获取我的功能组件的大小。这个项目正在使用 Typescript,所以我需要类型函数和其他东西。我尝试像这样使用useRef() 钩子:

function MyComponent (): JSX.Element {
  const targetREf = useRef<HTMLDivElement>() // I'm typing useRef like this.
  const [boxHeight, setBoxHeight] = useState()

  useLayoutEffect((): void => {
    setBoxHeight(targetRef.current && targetRef.current.getClientBoundingRect())
  }, [targetRef.current])
}

问题在于getClientBoundingRect()。

打字稿说:Property 'getClientBoundingRect' does not exist on type 'HTMLDivElement'.

我应该如何输入我的useRef() 来使用getClientBoundingReact?

我正在使用 React 16.8.6 和 Typescript 3.4.5。

谢谢!

【问题讨论】:

  • targetREf 不是HTMLDivElement,targetREf.current 是。您应该使用{ current: HTMLDivElement } 之类的东西,或者最好使用{ current: Element }。
  • 和旁注,useRef 是保持值 between 渲染(就像 useState 但更改值时不会触发重新渲染)。您不需要该功能,因此您可以初始化 const targetREf = React.createRef(); 只是为了明确意图,

标签: javascript reactjs typescript react-hooks react-functional-component


【解决方案1】:

我认为你拼错了函数的名称。它被称为:

getBoundingClientRect 不是 getClientBoundingReact。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 2021-04-02
    • 2020-04-08
    • 2021-09-10
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2023-01-03
    相关资源
    最近更新 更多