Flow Type complains about class property assigned via react ref

◇◆丶佛笑我妖孽 提交于 2021-02-11 14:39:42

问题


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│     };

回答1:


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)} />;
  }
}


来源:https://stackoverflow.com/questions/49248680/flow-type-complains-about-class-property-assigned-via-react-ref

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!