打字稿输入 onchange event.target.value [英] Typescript input onchange event.target.value

查看:45
本文介绍了打字稿输入 onchange event.target.value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 react 和 typescript 应用程序中,我使用:onChange={(e) =>data.motto = (e.target as any).value}.

In my react and typescript app, I use: onChange={(e) => data.motto = (e.target as any).value}.

我如何正确定义类的类型,这样我就不必使用 any 绕过类型系统?

How do I correctly define the typings for the class, so I wouldn't have to hack my way around the type system with any?

export interface InputProps extends React.HTMLProps<Input> {
...

}

export class Input extends React.Component<InputProps, {}> {
}

如果我输入 target: { value: string }; 我得到:

If I put target: { value: string }; I get :

ERROR in [default] /react-onsenui.d.ts:87:18
Interface 'InputProps' incorrectly extends interface 'HTMLProps<Input>'.
  Types of property 'target' are incompatible.
    Type '{ value: string; }' is not assignable to type 'string'.

推荐答案

通常事件处理程序应该使用 e.currentTarget.value,例如:

Generally event handlers should use e.currentTarget.value, e.g.:

onChange = (e: React.FormEvent<HTMLInputElement>) => {
    const newValue = e.currentTarget.value;
}

您可以在此处了解原因(还原使 SyntheticEvent.target 通用,而不是 SyntheticEvent.currentTarget.").

You can read why it so here (Revert "Make SyntheticEvent.target generic, not SyntheticEvent.currentTarget.").

UPD:正如@roger-gusmao 提到的 ChangeEvent 更适合输入表单事件.

UPD: As mentioned by @roger-gusmao ChangeEvent more suitable for typing form events.

onChange = (e: React.ChangeEvent<HTMLInputElement>)=> {
   const newValue = e.target.value;
}

这篇关于打字稿输入 onchange event.target.value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆