英文:
how do i type e.key and e.target.value with typescript in react
问题
我需要e.key和e.target.value,但似乎无法在这段代码中使其工作:
const handleInputKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
dfTextQuery(e.target.value)
}
};
为什么target
没有value
属性?而且我收到了一个错误消息:
属性'value'在类型'EventTarget'上不存在。
我期望使用HTMLInputElement,它应该可以工作。在React中如何使用TypeScript来为e.key和e.target.value指定类型?
英文:
i need e.key and e.target.value but i can't seem to make it work with this code:
const handleInputKeyPress = (e: React.KeyboardEvent<HTMLInputElement> ) => {
if(e.key ==='Enter') {
dfTextQuery(e.target.value)
}
};
why is target not having the value property? and i am getting an error:
> Property 'value' does not exist on type 'EventTarget'.
i was expecting with HTMLInputElement, it should work. how do i type e.key and e.target.value with typescript in react?
答案1
得分: 3
在浏览器中,事件会冒泡,从子元素传递到父元素。
你的事件中的 target
元素是原始事件的来源。
在你的情况下,键盘事件将从你的输入字段分发,永远不会来自其他子元素。
不要使用 target
,你可以使用 currentTarget
,它对应于侦听器附加的DOM元素。这将是你的输入字段,因此始终将是一个 HTMLInputElement。
英文:
In the browser, events are bubbling, going from child to parent.
the target
element from your event is the source of the original event.
In your case, the keyboard event will be dispatched from your input field, and will never come from another child.
Instead of using target
, you can use currentTarget
which corresponds to the DOM element on which the listener is attached. This will be your input field, and so will always be an HTMLInputElement.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论