我有两个组件:
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输入什么。
谢谢!
发布于 2020-10-11 08:16:39
您只需为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 (
...
);
});https://stackoverflow.com/questions/64298990
复制相似问题