[英]React - useRef with TypeScript and functional component
I was trying to call the child component method from parent component and I was trying to use useRef.我试图从父组件调用子组件方法,我试图使用 useRef。 In the future, the SayHi method will be update hook state in the child component.将来,SayHi 方法将更新子组件中的钩子状态。 Unfortunately, I have bugs with I can't deal with.不幸的是,我有无法处理的错误。
Line: ref.current.SayHi();行: ref.current.SayHi();
Property 'SayHi' does not exist on type 'ForwardRefExoticComponent<{ name: string;类型“ForwardRefExoticComponent<{ name: string;”上不存在属性“SayHi” } & RefAttributes<{ SayHi: () => void; } & RefAttributes<{ SayHi: () => void; }>>'. }>>'。
Line: < Child name="Adam" ref={ref}/>行: < Child name="Adam" ref={ref}/>
Type 'RefObject void;输入'RefObject void; }>>>' is not assignable to type '((instance: { SayHi: () => void; } | null) => void) | }>>>' 不能分配给类型 '((instance: { SayHi: () => void; } | null) => void) | RefObject<{ SayHi: () => void; RefObject<{ SayHi: () => void; }> | }> | null |空| undefined'.不明确的'。 Type 'RefObject void;输入'RefObject void; }>>>' is not assignable to type 'RefObject<{ SayHi: () => void; }>>>' 不能分配给类型 'RefObject<{ SayHi: () => void; }>'. }>'。 Property 'SayHi' is missing in type 'ForwardRefExoticComponent<{ name: string; “ForwardRefExoticComponent<{ name: string;”类型中缺少“SayHi”属性} & RefAttributes<{ SayHi: () => void; } & RefAttributes<{ SayHi: () => void; }>>' but required in type '{ SayHi: () => void; }>>' 但在类型 '{ SayHi: () => void; 中是必需的; }'. }'。
Full test.tsx file:完整的 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>;
});
I deeply ask for help on this topic.我深切地寻求有关此主题的帮助。
You require to extract the ref type elsewhere:您需要在别处提取 ref 类型:
interface RefObject {
SayHi: () => void
}
then just refer to it in both places然后在两个地方都引用它
const Child = forwardRef((props: {name: string}, ref: Ref<RefObject>)=> {
const {name} = props;
useImperativeHandle(ref, () => ({ SayHi }));
function SayHi() { console.log("Hello " + name); }
return <div>{name}</div>;
});
const Parent = () => {
const ref = useRef<RefObject>(null);
const onButtonClick = () => {
if (ref.current) {
ref.current.SayHi();
}
};
return (
<div>
<Child name="Adam" ref={ref}/>
<button onClick={onButtonClick}>Log console</button>
</div>
);
}
只需用这个const ref = useRef<{ SayHi: () => void }>(null);
替换你的ref
的声明const ref = useRef<{ SayHi: () => void }>(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.