javascript - 使用 ref 输入 React 组件? typescript

标签 javascript reactjs typescript

所以我有一个引用:

someComponent;

还有someComponent基本上是一个 React 组件,如下所示:

class SomeComponent<IProps> {
   getData = () => {};

   render() {
      ...some stuff
   }
}

那么,我该如何输入 someComponent所以如果我这样做:

this.someComponent.getData();

TypeScript不会大喊getData this.someComponent 上不存在?

我尝试过:

someComponent: React.RefObject<SomeComponent<IProps>>

但是 TypeScript 仍然警告我。

编辑:尝试使用 createRef,但是出现以下错误: enter image description here

最佳答案

在父组件中声明ref时需要指定组件的类型:

someComponent = React.createRef<SomeComponent>();

并将引用传递给渲染的组件:

<SomeComponent ref={this.someComponent} />

然后你可以像这样调用 getData:

if (this.someComponent.current !== null) {
  this.someComponent.current.getData()
}

关于javascript - 使用 ref 输入 React 组件? typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60571703/

相关文章:

reactjs - 从服务器 Laravel 和 reactjs 下载文件

javascript - 如何使用对象条目创建对象数组?

javascript - 原型(prototype)上的 Object.defineProperty 阻止 JSON.stringify 序列化它

javascript - 这是一个很好的 typescript 转换吗?为什么会出现这个错误?

javascript - 使用 Websocket 的 D3 的 OnClick() 处理程序

javascript - HandlebarJS 使用另一个属性的结果作为其他地方的名称

javascript - 我将如何使用 Socket-IO 上传图像文件?

javascript - 使用 jQuery 将 anchor 标记转换为纯文本

reactjs - 如何将 Google 的gapi 与Reactjs 结合使用?

Angular 5显示嵌套问题和答案在其父项目下显示项目