TypeScript输入onchange event.target.value

reactjs React.js

A十三

2020-03-12

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

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

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

第1004篇《TypeScript输入onchange event.target.value》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
老丝阿飞 2020.03.12
  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
  }

并确保您拥有"lib": ["dom"]自己的tsconfig

Mandy猪猪 2020.03.12

这是一种经过TS 3.3测试的ES6对象分解的方法。
本示例用于文本输入。

name: string = '';

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

target你试图在添加InputProps是不一样的target,你想这是在React.FormEvent

因此,我可以提出的解决方案是,扩展与事件相关的类型以添加​​目标类型,如下所示:

interface MyEventTarget extends EventTarget {
    value: string
}

interface MyFormEvent<T> extends React.FormEvent<T> {
    target: MyEventTarget
}

interface InputProps extends React.HTMLProps<Input> {
    onChange?: React.EventHandler<MyFormEvent<Input>>;
}

一旦有了这些类,就可以将输入组件用作

<Input onChange={e => alert(e.target.value)} />

没有编译错误。实际上,您还可以将上面的前两个接口用于其他组件。

Me无敌小哥 2020.03.12

as HTMLInputElement 为我工作

Eva西里 2020.03.12

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

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

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

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

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android