从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} />
)
}
}
Run Code Online (Sandbox Code Playgroud)
出现以下错误:
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].
Run Code Online (Sandbox Code Playgroud)
我该如何正确输入?
all*_*enx 21
查看React.createRef()的流类型定义:
declare export function createRef<ElementType: React$ElementType>(
): {current: null | React$ElementRef<ElementType>};
Run Code Online (Sandbox Code Playgroud)
我能够在我的代码中做这样的事情
/* @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} />
)
}
}
Run Code Online (Sandbox Code Playgroud)