【发布时间】: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