自React 16.3起,可以使用React.createRef()
来访问DOM元素。我也在我的项目中使用Flow,但documentation still uses the old way。
以下代码遗憾地失败了:
/* @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].
如何正确输入?
答案 0 :(得分:13)
查看React.createRef()的流类型定义:
canonical
我能够在我的代码中执行类似的操作
declare export function createRef<ElementType: React$ElementType>(
): {current: null | React$ElementRef<ElementType>};
答案 1 :(得分:1)
有一个相关的github issue。
如果尚未修复,您可以自行输入:
type RefObject = {|
current: any,
|};
这是react library type definitions内部输入的方式。
答案 2 :(得分:0)
如果您使用的是“类属性”,则可以通过以下方式createRef()
:
// @flow
import * as React from 'react';
export class TestComponent extends React.Component<{}> {
myRef = React.createRef<HTMLElement>();
render() {
return (
<div ref={this.myRef} />
)
}
}
答案 3 :(得分:0)
就我而言,我使用的是Formik参考
// @flow
import React from 'react';
import { Formik } from "formik"
export class TestComponent extends React.Component<Props> {
formikRef = React.createRef<Formik>();
render() {
return (
<Formik
...,
ref={this.formikRef}
/>
)
}
}