我使用 React 的 forwardRef
进行了 ref 转发,以下是我的代码:
interface PropsDummy {}
const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => {
console.log(ref.current);
}
但为什么会导致 TypeScript 错误?
Property 'current' does not exist on type '((instance: HTMLInputElement | null) => void) | MutableRefObject<HTMLInputElement | null>'
但是,如果我使用别名,那么当前的对象可以完美地运行而不会出现 TypeScript 错误。
interface PropsDummy {}
const ProfileMenu = forwardRef<HTMLInputElement, PropsDummy>((props, ref) => {
const myRef = ref as React.RefObject<HTMLInputElement>;
console.log(myRef.current);
}
如何在不出现 TypeScript 错误的情况下获取当前对象?
谢谢
forwardedRef
多次,我不想每次都检查forwardedRef是否为函数。有人知道另一个解决方案吗? - JunKim.current
的值放入useState
中,并将该状态传递给子组件。 - smac89