首页 > 解决方案 > 如何将 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].

如何正确输入?

标签: reactjsflowtype

解决方案


查看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} />
    )
  }
}

推荐阅读