首页 > 解决方案 > Flow 给出错误“无法将 [value] 分配给 this.[property],因为 [class] 中缺少属性 [property]”

问题描述

这有效:

// @flow
import React, {Component} from 'react';


type Props = {};

class Delete extends Component<Props> {
  targetElement: null | winndow.HTMLInputElement;

  constructor(props: Props) {
    super(props);

    this.targetElement = null; // initialize to null
  }

  handleClick = (e: SyntheticEvent<> & {target: window.HTMLInputElement}) => {
    this.targetElement = (e.target: window.HTMLInputElement).value;
  };

  render() {
    return (
      <input onClick={this.handleClick} value="hello" />
    );
  }
}

export default Delete;

但这不是:

...
handleClick = (e: SyntheticEvent<> & {target: window.HTMLInputElement}) => {
    this.targetElement = e.target.value;
  };
...

错误信息是:Cannot get e.target.value because property value is missing in EventTarget

1)我已经输入了“目标”属性window.HTMLInputElement,它有一个 value 属性,那么为什么 Flow 坚持认为 EventTarget 中缺少属性值为什么是 EventTarget?)

首先,在我添加 Flow 注释之前,代码运行良好,并且没有关于缺少属性的控制台错误。

我真的很困惑这是如何工作的 - 我已经阅读了 thisthis,似乎有大量的解决方法/解决方案,但我不确定它们为什么会起作用。此外,这些都是 2-3 岁,我不确定它们现在是否仍然相关。我是 Flow 的新手,但我真的很想掌握它!

标签: reactjsflowtype

解决方案


利用SyntheticInputEvent<*>

  handleClick = (e: SyntheticInputEvent<*>) => {
    this.targetElement = e.target.value;
  };

或者

  handleClick = (e: SyntheticEvent<HTMLInputElement>) => {
    this.targetElement = e.target.value;
  };

您可能想查看文档小抄表


推荐阅读