gpt4 book ai didi

javascript - 类型 'current' 上不存在属性 '((instance: HTMLDivElement | null) => void) | RefObject'

转载 作者:行者123 更新时间:2023-12-04 11:18:52 47 4
gpt4 key购买 nike

通常当我使用 React + Typescript 并且我必须使用 refs 时,我通常会使用这个检查:

const ref = useRef<HTMLDivElement>(null)
...
if(ref && ref.current)
但最近,我收到了这个错误:
Property 'current' does not exist on type '((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement>'.
Property 'current' does not exist on type '(instance: HTMLDivElement | null) => void'.ts(2339)
关于这个错误意味着什么的任何想法?为了解决这个问题,作为一种解决方法,我添加了第三个检查:
if(ref && "current" in ref && ref.current)
但这看起来很糟糕,主要是当您必须同时使用多个 refs 时。
谢谢你的帮助。

最佳答案

现代 React 中有两种 ref:ref 对象和 ref 回调。 Ref 对象是由 useRef 创建的。 (或在类组件中,createRef):它是一个带有 current 的对象属性(property)。在 typescript 中,这些类型为 RefObject<T> , 其中 Tcurrent 上的任何值.
Ref 回调是另一种选择,某些高级案例需要它。您将一个函数传递给元素,该函数将在创建或销毁实例时回调。它们的类型为 (instance: T) => void .
将 ref 对象和 ref 回调组合成一个类型的简写是 Ref<T> ,看起来这就是您的代码所期望的。由于您尚未显示该代码,因此我必须对其外观进行一些有根据的猜测。假设您有一个接受 ref 作为 prop 的组件(也许它可以将它交给它的内部组件之一):

interface ExampleProps {
buttonRef: Ref<HTMLButtonElement>
}

const Example: FC<ExampleProps> = ({ buttonRef }) => {
return (
<div>
<button ref={buttonRef}>Hello</button>
<div>
)
}
由于我已将 prop 定义为 Ref,因此可以在 ref 对象或 ref 回调中传递它。在这种情况下这很好,因为除了将它传递给按钮之外,我没有对它做任何事情。但是如果我尝试编写一些代码来与之交互,我不能假设它是一个对象或函数。
如果我需要这样做,也许我可以限制 Prop 所以它只需要 ref 对象,然后我可以假设它会有 .current
interface ExampleProps {
buttonRef: RefObject<HTMLButtonElement>
}

const Example: FC<ExampleProps> = ({ buttonRef }) => {
useEffect(() => {
console.log(buttonRef.current);
});
return (
<div>
<button ref={buttonRef}>Hello</button>
<div>
)
}
但也许我不想限制我的组件的使用方式,但我仍然需要能够以某种方式与 ref 交互。在这种情况下,我可能需要自己创建一个回调 ref,然后向其中添加逻辑来处理我对 ref 的使用以及 prop 对 ref 的使用:
interface ExampleProps {
buttonRef: Ref<HTMLButtonElement>
}

const Example: FC<ExampleProps> = ({ buttonRef }) => {
const myRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
console.log(myRef.current);
});
return (
<div>
<button ref={(element) => {
(myRef as MutableRefObject<HTMLButtonElement>).current = element;
if (typeof buttonRef === 'function') {
buttonRef(element);
} else {
buttonRef.current = element;
}
}}>Hello</button>
<div>
)
}
as MutableRefObject<HTMLButtonElement> 的类型断言需要,因为 myRef被标记为不可变。这种类型反射(reflect)了只有 react 应该修改 .current 的事实。属性(property)。这对于正常的用例来说是好的,但是由于我们从 react 中接管了这个责任,所以改变值是可以的。

关于javascript - 类型 'current' 上不存在属性 '((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65876809/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com