TypeScript 中的“EventTarget”上不存在属性“value”

IT技术 reactjs typescript events
2021-05-16 14:05:52

带有 React 的 TypeScript 中的以下代码输出以下错误。

类型“EventTarget”上不存在属性“value”。

import React, { Component } from 'react';

class InputForm extends React.Component<any ,any> {
  state = {
    userInput: ''
  };

  handleUserInput = (e: React.FormEvent<HTMLInputElement>): void => {
    this.setState({
      userInput: e.target.value
    });
  }

  // Working code from 42081549
  // Not relevant to this project
  update = (e: React.FormEvent<HTMLInputElement>): void => {
    this.props.login[e.currentTarget.name] = e.currentTarget.value
  }

  submitMessage = (e: React.FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    this.props.sendUserMessage(this.state.userInput)
  }

  render() {
    return (
      <form className="chat-input-form" onSubmit={this.submitMessage}>
        <input value={this.state.userInput} onChange={this.handleUserInput}/>
        <button type="submit" />
      </form>
    );
  }

}

export default InputForm;

我目前正在使用:

  • "@types/react": "^16.0.40",

  • “react”:“^ 16.2.0”,

  • "typescript": "^2.7.2",

这可以被认为是Typescript: React event types的后续,但是它不是重复的,因为Nitzan Tomer这个答案中提供的工作代码目前在我的特定用例中不起作用。

编辑如上所述,不是Typescript: React event types的副本,该问题中提供的解决方案在这种情况下不起作用,因此可能是不同的原因。

我的 tsconfig.json 文件如下:

{
  "compilerOptions": {
    "target": "es5",                          
    "module": "commonjs", 
    "lib": ["esnext", "dom"],
    "jsx": "react",                           
    "sourceMap": true,                        
    "outDir": "./dist/",                      
    "strict": true,                        
    "noImplicitAny": true,                   
    "esModuleInterop": true                 
  }
}
2个回答

问题是您正在使用e.target.value而不是e.currentTarget.value.

正如您在定义文件中看到的

interface SyntheticEvent<T> {
    ...
    currentTarget: EventTarget & T;
    ...
    target: EventTarget;
    ...
}

详细说明 Nitzan Tomer 的回答......

曾经能够以e.target.value这种方式使用目标是通用的,在这种情况下:HTMLInputElement. 代码已恢复为e.currentTarget通用和e.target非通用(硬编码为 EventTarget)。EventTarget 没有 value 属性。

原因在于currentTarget之间的区别target当您提到 时target,您指的是触发事件的元素。如果你有一个按钮,里面有一些图标。如果直接点击图标,那么它就是目标。在编译时,您无法知道哪种元素类型会触发点击,但您可以知道 eventListener 注册在哪个元素上。因此currentTarget是通用的。

此外,target很少是您想要的。您通常需要在其中附加 eventListener 的元素。

提供上述理由Github 评论
目标设为/ 非 / 通用Github PR