[英]Type React component with ref? Typescript
So I have a ref:所以我有一个参考:
someComponent;
And the someComponent
is basically a React component that looks like: someComponent
基本上是一个 React 组件,如下所示:
class SomeComponent<IProps> {
getData = () => {};
render() {
...some stuff
}
}
So, how can I type someComponent
so if I do:那么,如果我这样做,我该如何输入
someComponent
:
this.someComponent.getData();
The TypeScript
won't shout that getData
doesn't exist on this.someComponent
? TypeScript
不会大喊this.someComponent
上不存在getData
吗?
I tried:我试过:
someComponent: React.RefObject<SomeComponent<IProps>>
But TypeScript still warns me.但是 TypeScript 仍然警告我。
Edit : Tried with createRef, however getting following error:编辑:尝试使用 createRef,但出现以下错误:
You need to specify the type of the component when you declare the ref in the parent component:在父组件中声明 ref 时需要指定组件的类型:
someComponent = React.createRef<SomeComponent>();
And pass the ref to the rendered component:并将 ref 传递给渲染的组件:
<SomeComponent ref={this.someComponent} />
Then you can call getData like this:然后你可以像这样调用 getData :
if (this.someComponent.current !== null) {
this.someComponent.current.getData()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.