[英]How would you correctly set up a TypeScript declaration when using "useCallback" for a callback ref?
I'm working on a React + TypeScript project where I've pulled in the provided " How can I measure a DOM node? " example, but I don't seem to be able to get React's types to acknowledge a scenario where someone would be passing in the return value of useCallback
as a ref
.我正在开发一个 React + TypeScript 项目,我在其中引入了提供的“ 我如何测量 DOM 节点? ”示例,但我似乎无法让 React 的类型承认有人会将
useCallback
的返回值作为ref
useCallback
。 I've recreated a bare-bones usage of it in this CodeSandbox .我在这个 CodeSandbox 中重新创建了它的基本用法。 If you open this you should see the TypeScript error indicator on this line:
如果你打开它,你应该在这一行看到 TypeScript 错误指示器:
<div ref={ref} className="App">
How exactly should the types be set up to make this valid, or is there something missing in the @types/react
package?究竟应该如何设置类型以使其有效,或者
@types/react
包中是否缺少某些内容?
First add null
to the type of the node inside useCallback
and add as const
to the returned array which will type the returned array as a tuple(remember the order of types) instead of making it an array of multiple types首先在
useCallback
中的节点类型中添加null
并将as const
添加到返回的数组中,这会将返回的数组类型为元组(记住类型的顺序),而不是使其成为多种类型的数组
function useClientRect() {
const [rect, setRect] = useState<ClientRect>();
const ref = useCallback((node: HTMLElement | null) => {
if (node !== null) {
setRect(node.getBoundingClientRect());
}
}, []);
return [rect, ref] as const;
}
Set returning type for useClientRect
hook to [ClientRect | undefined, (node: HTMLDivElement) => void]
将
useClientRect
钩子的返回类型设置为[ClientRect | undefined, (node: HTMLDivElement) => void]
[ClientRect | undefined, (node: HTMLDivElement) => void]
and change arguments type for useCallback
to HTMLDivElement
: [ClientRect | undefined, (node: HTMLDivElement) => void]
并将useCallback
参数类型useCallback
为HTMLDivElement
:
// packages
import { useCallback, useState } from "react";
function useClientRect(): [
ClientRect | undefined,
(node: HTMLDivElement) => void
] {
const [rect, setRect] = useState<ClientRect>();
const ref = useCallback((node: HTMLDivElement) => {
if (node !== null) {
setRect(node.getBoundingClientRect());
}
}, []);
return [rect, ref];
}
export default useClientRect;
In your use-client-react
you have passed ClientRect
as a type which doesn't exist.在您的
use-client-react
您已将ClientRect
作为不存在的类型传递。 The following works for me fine.以下对我来说很好。
import { useCallback, useState } from "react";
function useClientRect() {
const [rect, setRect] = useState();
const ref = useCallback((node: HTMLDivElement) => {
if (node !== null) {
setRect(node.getBoundingClientRect());
}
}, []);
return [rect, ref];
}
export default useClientRect;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.