在我的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'.

当前回答

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

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

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

其他回答

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

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

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

const handleChange = (
    e: ChangeEvent<HTMLInputElement>
  ) => {
    const { name, value } = e.target;
    this.setState({ ...currentState, [name]: value });
  };

您可以将此应用于表单组件中的每个输入元素

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

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

下面是ES6对象解构的一种方法,用TS 3.3测试。 这个例子是一个文本输入。

name: string = '';

private updateName({ target }: { target: HTMLInputElement }) {
    this.name = target.value;
}

>是typescript中更改事件的类型。事情是这样的

import { ChangeEvent } from 'react';

const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    setValue(event.target.value);
};