简体   繁体   中英

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:

// 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: 在此处输入图像描述 I marked my confusion in the screenshot: event.currentTarget is null, but event.currentTarget.files is accessible? How is that possible?

Taken from the Event.currentTarget documentation

Note: The value of event.currentTarget is only available while the event is being handled. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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