简体   繁体   English

EventTarget 类型上不存在属性“值”(ts2339)

[英]Property 'value' does not exist on type EventTarget (ts2339)

I am getting squigglies:我越来越曲折:

在此处输入图像描述

You can see I'm typing it right (I think).你可以看到我输入正确(我认为)。

  const hClick = (e:React.MouseEvent<HTMLButtonElement>)=>{
    console.log(e.target.value)
  }

Here's the element in question.这是有问题的元素。

      {props.question.responses.map((r: string, i: number) => {
        return <button key={i} value={r} className={`${CSS.columnBtn} ${CSS.gray}`} onClick={(e) => hClick(e)}>{r}</button>;
      })}

You can see it clearly has a value.您可以清楚地看到它具有价值。 I also did my research.我也做了我的研究。 Not only do buttons have values natively but MS said in their docs they have a value prop as does the general button element per Mozilla and when I ctrl + clicked into the d.ts file for HTMLButtonElement, it shows a value prop that's a string:按钮不仅本身具有值,而且 MS 在他们的文档中说它们有一个值道具,每个 Mozilla 的一般按钮元素也是如此,当我 ctrl + 单击进入 HTMLButtonElement 的 d.ts 文件时,它显示一个值道具,它是一个字符串:

    /**
     * Sets or retrieves the default or selected value of the control.
     */
    value: string;

Morever the code works and it logs the value.此外,代码可以正常工作并记录值。 I'm pretty new to TypeScript so there's probably something I don't know, and that's what I want to learn.我是 TypeScript 的新手,所以可能有些东西我不知道,而这正是我想学习的。

BTW if a property doesn't exist in a given element but you give it a custom one, it obviously won't be in the d.ts so how would you tell the compiler that your html attribute foo[="bar"] exists on the event?顺便说一句,如果一个属性在给定元素中不存在,但你给它一个自定义的,它显然不会在 d.ts 中,那么你如何告诉编译器你的 html 属性 foo[="bar"] 存在在活动上?

Since target could be any other potential element (or even a non-element) you can use a Type Assertion to make it into HTMLButtonElement .由于target可以是任何其他潜在元素(甚至是非元素),您可以使用类型断言将其变为HTMLButtonElement

const hClick = (e:React.MouseEvent<HTMLButtonElement>)=>{
    let button = e.target as HTMLButtonElement;
    console.log(button.value)
}

I look on the React Typings and the HTMLButtonElement will end up in currentTarget (which makes sense because that's the element the listener is attached to which is a button).我查看了 React Typings 并且HTMLButtonElement最终会出现在currentTarget中(这是有道理的,因为这是侦听器所附加的元素,它是一个按钮)。

So you can just use:所以你可以使用:

const hClick = (e:React.MouseEvent<HTMLButtonElement>)=>{
    console.log(e.currentTarget.value)
}

<input (keyup)="myeventreal($any($event).target.value)" /> <input (keyup)="myeventreal($any($event).target.value)" />

use this in angluar 13 version在 angluar 13 版本中使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM