[英]How do I type a ref callback with useCallback (with Typescript)?
I'm new to Typescript and can't figure out how to type this situation.我是 Typescript 的新手,不知道如何输入这种情况。 I'm writing a custom hook and trying to create a callback ref.
我正在编写一个自定义钩子并尝试创建一个回调引用。 My problem is that this function sets the ref's
current
, and returns nothing, but since I use it as a ref, typescript yells at me Property 'current' is missing in type '(node: any) => void' but required in type 'RefObject<HTMLDivElement>'
.我的问题是这个 function 设置了 ref 的
current
,并且什么都不返回,但是因为我将它用作 ref,所以 typescript 对我大喊Property 'current' is missing in type '(node: any) => void' but required in type 'RefObject<HTMLDivElement>'
。
Thank you in advance.先感谢您。
This is the code:这是代码:
import React, {useCallback, useRef} from 'react'
const useCustom = (): [RefObject<HTMLDivElement>] => {
const ref = useRef<HTMLDivElement | null>(null)
const setRef = useCallback(node => {
....
ref.current = node
}, [])
return [setRef]
}
const SomeComp = () => {
const [ref] = useCustom()
return <div ref={ref}>Text</div>
}
The problem is you said the return value of useCustom
would be RefObject<HTMLDivElement>
, but returned (node: HTMLDivElement) => void
.问题是您说 useCustom 的返回值是
useCustom
RefObject<HTMLDivElement>
,但返回(node: HTMLDivElement) => void
。
Your custom hook should return 2 values: one for setting the ref value, the other for the ref itself.您的自定义挂钩应返回 2 个值:一个用于设置 ref 值,另一个用于 ref 本身。 So it will look like
useState
hook:所以它看起来像
useState
钩子:
const useCustom = (): [
RefObject<HTMLDivElement>,
(node: HTMLDivElement) => void
] => {
const ref = useRef<HTMLDivElement | null>(null);
const setRef = useCallback((node) => {
ref.current = node;
}, []);
return [ref, setRef];
};
I propose a different solution.我提出了一个不同的解决方案。
This is assuming the author is trying to use a "callback ref" to execute a side effect, when the ref changes.这是假设作者在 ref 更改时尝试使用“回调 ref”来执行副作用。 When using two return values the ref might still accidentally be set (by using the
ref
) without executing the callback ( setRef
), which I'm guessing is not the author's intention.当使用两个返回值时,可能仍会意外设置 ref(通过使用
ref
)而不执行回调( setRef
),我猜这不是作者的意图。
Typing things like this seems to work as expected (using author's example):键入这样的内容似乎可以按预期工作(使用作者的示例):
import React, {useCallback, useRef} from 'react'
const useCustom = (): [React.RefCallback<HTMLElement>] => {
const ref = useRef<HTMLElement | null>(null)
const setRef: React.RefCallback<HTMLElement> = useCallback(node => {
....
ref.current = node
}, [])
return [setRef]
}
const SomeComp = () => {
const [ref] = useCustom()
return <div ref={ref}>Text</div>
}
Note: I also changed HTMLDivElement
to HTMLElement
to make the hook more universal.注意:我还将
HTMLDivElement
更改为HTMLElement
以使钩子更加通用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.