reactjs - 如何将 Flow 与 React.createRef() 一起使用?
问题描述
从 React 16.3 开始,它可以React.createRef()
用来访问 DOM 元素。我也在我的项目中使用Flow,但文档仍然使用旧方式。
不幸的是,下面的代码失败了:
/* @flow */
import * as React from 'react';
export class TestComponent extends React.Component<{}> {
myRef: React.Ref<HTMLDivElement>
constructor(props: any) {
super(props)
this.myRef = React.createRef()
}
render() {
return (
<div ref={this.myRef} />
)
}
}
出现以下错误:
Cannot instantiate `Ref` because in type argument `ElementType`:
- Either a callable signature is missing in `HTMLDivElement` [1] but exists in
`React.StatelessFunctionalComponent` [2].
- Or `HTMLDivElement` [1] is incompatible with statics of `React.Component` [3].
如何正确输入?
解决方案
查看React.createRef()的流类型定义:
declare export function createRef<ElementType: React$ElementType>(
): {current: null | React$ElementRef<ElementType>};
我能够做这样的事情:
/* @flow */
import * as React from 'react';
export class TestComponent extends React.Component<{}> {
myRef: { current: null | HTMLDivElement }
constructor(props: any) {
super(props)
this.myRef = React.createRef()
}
render() {
return (
<div ref={this.myRef} />
)
}
}
推荐阅读
- android - 在某些设备中更改 scalex 和 scaley 时,Android MotionLayout 使应用程序滞后
- python - 在 Python Flask 会话中成功登录和令牌检索后,Microsoft 图形 API 不保存会话令牌
- arrays - 如果初始化为 Array[] = "testit",如何存储字符数组
- json - 如何修剪 Google Apps 脚本输出
- c# - 求解矩阵方程 - 3 点圆
- node.js - 无法使用 PM2 启动节点服务器
- javascript - 如何切换图像 onmouseover/onmouseout?
- haskell - Haskell如何确定表达式是否简单?
- javascript - 如何将 googlesheets 单元格的值添加到 HTML
- python - 将整个列表转换为字符串