在我的react和typescript应用程序中,我使用:

onChange={(e) => data.motto = (e.target as any).value}

我如何正确地定义类的类型,这样我就不必用任何类型系统来破解我的方法?

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

}

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

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

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'.

当前回答

还没有提到的另一种方法是输入onChange函数,而不是它接收到的道具。使用反应。ChangeEventHandler:

const stateChange: React.ChangeEventHandler<HTMLInputElement> = (event) => {
    console.log(event.target.value);
};

其他回答

由于@haind

是的HTMLInputElement为输入字段工作

//Example
var elem = e.currentTarget as HTMLInputElement;
elem.setAttribute('my-attribute','my value');
elem.value='5';

这个htmllinputelement的接口是继承自HTMLElement的,而HTMLElement是继承自根级别的EventTarget的。因此,我们可以根据上下文断言使用作为操作符来使用特定的接口,比如在这种情况下,我们使用HTMLInputElement作为输入字段,其他接口可以是HTMLButtonElement, HTMLImageElement等。

更多的参考,你可以检查其他可用的接口在这里

Mozilla的Web API接口 微软提供的外部节点模块接口

as HTMLInputElement为我工作

我们还可以使用onChange事件触发定义的类型(在函数组件中),如下所示:

 const handleChange = (
    e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
  ) => {
        const name = e.target.name;
        const value = e.target.value;
};

您可以执行以下操作:

import { ChangeEvent } from 'react';

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

如果你这样做,你不需要输入:

<input onChange={(event) => { setValue(e.target.value) }} />

因为如果你直接在html标签中使用箭头函数设置了一个新值,typescript将默认理解事件的类型。