【问题标题】:How to use Flow with React.createRef()?如何将 Flow 与 React.createRef() 一起使用?
【发布时间】:2018-10-09 02:41:45
【问题描述】:

从 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].

如何正确输入?

【问题讨论】:

标签: reactjs flowtype


【解决方案1】:

就我而言,我使用的是 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}
         />
     )
  }
}

【讨论】:

  • 是的,这里的类型箭头修复了它:const formRef = React.useRef&lt;?HTMLFormElement&gt;(null);
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    如果您使用“类属性”,您可以通过以下方式createRef()

    // @flow
    import * as React from 'react';
    
    export class TestComponent extends React.Component<{}> {
      myRef = React.createRef<HTMLElement>();
    
      render() {
        return (
          <div ref={this.myRef} />
        )
      }
    }
    

    【讨论】:

      【解决方案4】:

      有一个相关的github issue

      如果尚未修复,您可以自己输入:

      type RefObject = {|
        current: any,
      |};
      

      这是在react library type definitions 内部输入的方式。

      【讨论】:

      • 尝试使用自定义的 RefObject 时出现错误 Cannot assign React.createRef() to this.myRef because inexact object type [1] is incompatible with exact RefObject [2]. 知道吗? (我对流量很陌生)。
      • @Zardoz 试试这样:type RefObject = { current: any };
      猜你喜欢
      • 2020-12-22
      • 1970-01-01
      • 2018-05-27
      • 2012-08-13
      • 2020-01-08
      • 2017-08-29
      • 1970-01-01
      • 2015-11-18
      • 2019-03-31
      相关资源
      最近更新 更多