gpt4 book ai didi

reactjs - Typescript 输入 onchange event.target.value

转载 作者:搜寻专家 更新时间:2023-10-30 20:28:54 24 4
gpt4 key购买 nike

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

最佳答案

一般事件处理器应该使用e.currentTarget.value,例如:

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

您可以在此处阅读其中的原因 (Revert "Make SyntheticEvent.target generic, not SyntheticEvent.currentTarget.")。

UPD:如@roger-gusmao 所述,ChangeEvent 更适合输入表单事件。

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

关于reactjs - Typescript 输入 onchange event.target.value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40676343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com