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

当前回答

这也适用于我,它是框架不可知论者。

const handler = (evt: Event) => {
  console.log((evt.target as HTMLInputElement).value))
}

其他回答

const event = { target: { value: 'testing' } as HTMLInputElement };
handleChangeFunc(event as ChangeEvent<HTMLInputElement>);

这对我很有用。

  function handle_change(
    evt: React.ChangeEvent<HTMLInputElement>
  ): string {
    evt.persist(); // This is needed so you can actually get the currentTarget
    const inputValue = evt.currentTarget.value;

    return inputValue
  }

并确保在tsconfig中有"lib": ["dom"]。

一般情况下,事件处理程序应该使用e. currentarget。值,例如:

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

你可以在这里读到为什么会这样(还原“Make SyntheticEvent。target generic,而不是syntheticevent . currentarget .")。

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

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

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

name: string = '';

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

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

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