I need to set a state field which I get from an event, but it doesn\'t get set when I pass a function to it. The component and method looks like the following:
That's the expected behaviour, because event.persist() doesn't imply that currentTarget is not being nullified, in fact it should be - that's compliant with browser's native implementation.
This means that if you want to access currentTarget in async way, you need to cache it in a variable as you did in your answer.
To cite one of the React core developers - Sophie Alpert.
currentTarget changes as the event bubbles up – if you had a event handler on the element receiving the event and others on its ancestors, they'd see different values for currentTarget. IIRC nulling it out is consistent with what happens on native events; if not, let me know and we'll reconsider our behavior here.
Check out the source of the discussion in the official React repository and the following snippet provided by Sophie that I've touched a bit.
var savedEvent;
var savedTarget;
divb.addEventListener('click', function(e) {
savedEvent = e;
savedTarget = e.currentTarget;
setTimeout(function() {
console.log('b: currentTarget is now ' + e.currentTarget);
}, 0);
}, false);
diva.addEventListener('click', function(e) {
console.log('same event object? ' + (e === savedEvent));
console.log('same target? ' + (savedTarget === e.currentTarget));
setTimeout(function() {
console.log('a: currentTarget is now ' + e.currentTarget);
}, 0);
}, false);
div {
padding: 50px;
background: rgba(0,0,0,0.5);
color: white;
}
JS Bin
Click me and see output!