我试图使用useRef
从父组件调用子组件方法。
未来,SayHi
方法将在子组件中更新钩子状态。不幸的是,我无法处理错误。
行:ref.current.SayHi();
属性“SayHi”不存在于类型“ForwardRefExoticComponent<{ name: string; } & RefAttributes<{ SayHi: () => void; }>>”上。
行:<Child name="Adam" ref={ref}/>
类型“RefObject<ForwardRefExoticComponent<{ name: string; } & RefAttributes<{ SayHi: () => void; }>>>”不能分配给类型“((instance: { SayHi: () => void; } | null) => void) | RefObject<{ SayHi: () => void; }> | null | undefined”。“RefObject<ForwardRefExoticComponent<{ name: string; } & RefAttributes<{ SayHi: () => void; }>>>”不能分配给类型“RefObject<{ SayHi: () => void; }>”。类型“ForwardRefExoticComponent<{ name: string; } & RefAttributes<{ SayHi: () => void; }>>”中缺少属性“SayHi”,但在类型“{ SayHi: () => void; }”中是必需的。
完整的test.tsx
文件:
import React, { useRef, forwardRef, useImperativeHandle, Ref } from 'react'
const Parent = () => {
const ref = useRef<typeof Child>(null);
const onButtonClick = () => {
if (ref.current) {
ref.current.SayHi();
}
};
return (
<div>
<Child name="Adam" ref={ref}/>
<button onClick={onButtonClick}>Log console</button>
</div>
);
}
const Child = forwardRef((props: {name: string}, ref: Ref<{SayHi: () => void}>)=> {
const {name} = props;
useImperativeHandle(ref, () => ({ SayHi }));
function SayHi() { console.log("Hello " + name); }
return <div>{name}</div>;
});
我在这个话题上深切地请求帮助。