本文介绍了流类型抱怨通过react ref分配的类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始在使用create-react-app工具创建的项目上使用Flow类型.我努力使一个简单的方案工作,在类方法中,类属性被render方法中的元素引用填充,但是会引发2个错误.我究竟做错了什么?所有检查均应防止那些警告.

I've started using Flow type on top of a project created with create-react-app tool. I struggle to make a simple scenario work where a class property is filled with element reference in render method but throws 2 errors. What am I doing wrong? All the checks should prevent those warnings.

class MyComponent extends React.Component<*> {
  input: ?HTMLInputElement;

  componentDidUpdate = () => {
    if (this.input) {
        this.input.focus();
        if (this.input.value) {
            const valueLength = this.input.value.length;
            this.input.setSelectionRange(valueLength, valueLength);
        }
    }
  };

  render() {
    return <input ref={ref => (this.input = ref)} />;
  }
}

     Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ src/todo/index.js:38:28

 Property value is missing in null or undefined [1].

  [1] 33│     input: ?HTMLInputElement;
      34│
      35│     componentDidUpdate = () => {
      36│         if (this.input) {
      37│             this.input.focus();
      38│             if (this.input.value) {
      39│                 const valueLength = this.input.value.length;
      40│                 this.input.setSelectionRange(valueLength, valueLength);
      41│             }


 Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ src/todo/index.js:40:28

 Cannot call this.input.setSelectionRange because property setSelectionRange is missing in null or undefined [1].

  [1] 33│     input: ?HTMLInputElement;
      34│
      35│     componentDidUpdate = () => {
      36│         if (this.input) {
      37│             this.input.focus();
      38│             if (this.input.value) {
      39│                 const valueLength = this.input.value.length;
      40│                 this.input.setSelectionRange(valueLength, valueLength);
      41│             }
      42│         }
      43│     };

推荐答案

由于您正在调用方法,因此flow假设情况随时可能发生变化.您需要保留对输入的引用,然后一切都很好.如下所示:

Since you're calling methods, flow assumes that things could change at anytime. You need to keep a reference to the input and then you're all good. Something like below:

class MyComponent extends React.Component<*> {
  input: ?HTMLInputElement;

  componentDidUpdate = () => {
    const { input } = this

    if (input) {
        input.focus();
        if (input.value) {
            const valueLength = input.value.length;
            input.setSelectionRange(valueLength, valueLength);
        }
    }
  };

  render() {
    return <input ref={ref => (this.input = ref)} />;
  }
}

这篇关于流类型抱怨通过react ref分配的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:45
查看更多