Как использовать Flow с React.createRef ()? - PullRequest
0 голосов
/ 28 апреля 2018

Начиная с 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].

Как правильно набрать текст?

Ответы [ 3 ]

0 голосов
/ 30 июня 2018

Просмотр определения типа потока для 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} />
    )
  }
}
0 голосов
/ 08 мая 2019

Если вы используете «свойства класса», вы можете createRef() следующим образом:

// @flow
import * as React from 'react';

export class TestComponent extends React.Component<{}> {
  myRef = React.createRef<HTMLElement>();

  render() {
    return (
      <div ref={this.myRef} />
    )
  }
}
0 голосов
/ 28 апреля 2018

Есть связанная проблема github .

Если он еще не исправлен, вы можете ввести его самостоятельно:

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

Это то, как он вводится внутри в определения типа библиотеки реагирования .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...