Typescript - forward and useref



我有两个组件:

const ComponentOne = () => {
const a = React.useRef<ComponentTwo>(null);
// ^^^^^^^^^^ throws error - ComponentTwo refers to a value but used as type here
const fn = () => {
a.current.open(); // how to type it so typescript knows than open() is a function
a.current.awdokawd(); // typescript should throw error here
};
return (
<ComponentTwo ref={a} />
);
}
const ComponentTwo = React.forwardRef((props, ref: React.RefObject<What here?>) => {
// ^^^^ what to type here?
React.useImperativeHandle(ref, () => ({
open: () => {
console.log('hey');
},
}));
return (
...
);
});

正如您所看到的,我不确定useRef要输入什么,所以typescript可以正确地识别组件及其方法。也不确定用forwardRef键入什么。

谢谢!

您只需为ref:声明一个新类型

interface ComponentTwoRef {
open(): void;
}
const ComponentOne = () => {
const a = React.useRef<ComponentTwoRef>(null);
const fn = () => {
a.current.open();
a.current.awdokawd(); // typescript should throw error here
};
return (
<ComponentTwo ref={a} />
);
}
const ComponentTwo = React.forwardRef((props, ref: React.RefObject<ComponentTwoRef>) => {
React.useImperativeHandle(ref, () => ({
open: () => {
console.log('hey');
},
}));
return (
...
);
});

最新更新