【发布时间】:2019-07-11 02:41:17
【问题描述】:
我正在尝试为onKeyPress 事件编写一个类型正确的回调函数。
我尝试为函数或事件提供各种类型,但我似乎无法让事件e 被识别为同时具有key 字段和target.value 字段。
案例一:
const onKeyPress: React.KeyboardEventHandler = async (e) => {
if (e.key === "Enter") {
console.log(e.target.value);
}
};
消息:
TS2339:“EventTarget”类型上不存在属性“值”。
案例2:
const onKeyPress = async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
console.log(e.target.value);
}
};
消息:
TS2339:“EventTarget”类型上不存在属性“值”。
案例3:
事实证明,即使编写这个简单的 JSX 也会抛出同样的错误:
<input type="text" onKeyPress={(e) => {
const key = e.key;
const val = e.target.value;
}}/>
环境
来自package.json:
"@types/react": "^16.8.3"
“反应”:“^16.8.2”
"react-dom": "^16.8.2"
TypeScript 3.2.1.
有什么线索吗?
更新
接受的答案使我找到了这段工作代码:
const onKeyPress = async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
console.log(`Received: ${e.currentTarget.value}`);
await doAsyncStuff(e.currentTarget.value);
}
};
【问题讨论】:
标签: reactjs typescript-typings