tom*_*hes 12 events typescript reactjs
带有 React 的 TypeScript 中的以下代码输出以下错误。
类型“EventTarget”上不存在属性“value”。
import React, { Component } from 'react';
class InputForm extends React.Component<any ,any> {
state = {
userInput: ''
};
handleUserInput = (e: React.FormEvent<HTMLInputElement>): void => {
this.setState({
userInput: e.target.value
});
}
// Working code from 42081549
// Not relevant to this project
update = (e: React.FormEvent<HTMLInputElement>): void => {
this.props.login[e.currentTarget.name] = e.currentTarget.value
}
submitMessage = (e: React.FormEvent<HTMLFormElement>): void => {
e.preventDefault();
this.props.sendUserMessage(this.state.userInput)
}
render() {
return (
<form className="chat-input-form" onSubmit={this.submitMessage}>
<input value={this.state.userInput} onChange={this.handleUserInput}/>
<button type="submit" />
</form>
);
}
}
export default InputForm;
Run Code Online (Sandbox Code Playgroud)
我目前正在使用:
"@types/react": "^16.0.40",
“反应”:“^ 16.2.0”,
"打字稿": "^2.7.2",
这可以被认为是Typescript: React event types的后续,但是它不是重复的,因为Nitzan Tomer在这个答案中提供的工作代码目前在我的特定用例中不起作用。
编辑如上所述,不是Typescript: React event types的副本,该问题中提供的解决方案在这种情况下不起作用,因此可能是不同的原因。
我的 tsconfig.json 文件如下:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["esnext", "dom"],
"jsx": "react",
"sourceMap": true,
"outDir": "./dist/",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true
}
}
Run Code Online (Sandbox Code Playgroud)
Nit*_*mer 13
问题是您正在使用e.target.value
而不是e.currentTarget.value
.
正如您在定义文件中看到的:
interface SyntheticEvent<T> {
...
currentTarget: EventTarget & T;
...
target: EventTarget;
...
}
Run Code Online (Sandbox Code Playgroud)
详细说明 Nitzan Tomer 的回答......
您曾经能够以e.target.value
这种方式使用目标是通用的,在这种情况下:HTMLInputElement
. 代码已恢复为e.currentTarget
通用和e.target
非通用(硬编码为 EventTarget)。EventTarget 没有 value 属性。
原因在于currentTarget
和之间的区别target
。当您提到 时target
,您指的是触发事件的元素。如果你有一个按钮,里面有一些图标。如果直接点击图标,那么它就是目标。在编译时,您无法知道哪种元素类型会触发点击,但您可以知道 eventListener 注册在哪个元素上。因此currentTarget
是通用的。
此外,target
很少是您想要的。您通常需要附加 eventListener 的元素。
提供上述理由的Github 评论。
将目标设为/ 非 / 通用的Github PR。
归档时间: |
|
查看次数: |
10528 次 |
最近记录: |