简体   繁体   English

我怎么能访问和使用 event.currentTarget 但是当我打印事件时 currentTarget 是 null?

[英]How can it be that I can access and use event.currentTarget but when I print the event then currentTarget is null?

Consider the following code in React:考虑 React 中的以下代码:

// rendered:
<input type="file" onChange={onFileSelected} />

// Event handler:
function onFileSelected(event: ChangeEvent<HTMLInputElement>) {
  console.log('event:');
  console.log(event);
  console.log('event.currentTarget.files:');
  console.log(event.currentTarget.files);
}

Now after selecting a file on my onFileSelected function is triggered, this is the output:现在在我的onFileSelected function 上选择一个文件后触发,这是 output: 在此处输入图像描述 I marked my confusion in the screenshot: event.currentTarget is null, but event.currentTarget.files is accessible?我在屏幕截图中标记了我的困惑: event.currentTarget is null,但是event.currentTarget.files可以访问吗? How is that possible?这怎么可能?

Taken from the Event.currentTarget documentation取自Event.currentTarget 文档

Note: The value of event.currentTarget is only available while the event is being handled.注意: event.currentTarget 的值仅在处理事件时可用。 If you console.log() the event object, storing it in a variable, and then look for the currentTarget key in the console, its value will be null.如果您 console.log() 事件 object,将其存储在变量中,然后在控制台中查找 currentTarget 键,其值将是 null。 Instead, you can either directly console.log(event.currentTarget) to be able to view it in the console or use the debugger statement, which will pause the execution of your code thus showing you the value of event.currentTarget.相反,您可以直接使用 console.log(event.currentTarget) 以便能够在控制台中查看它或使用调试器语句,这将暂停代码的执行,从而向您显示 event.currentTarget 的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM