React.js onClick event returning all null values
React pools event objects for performance reasons. So it takes an event object from the pool, sets properties on it, calls your handler, and then sets all of the properties to null so it can be reused.
This is mostly only a problem because the console
lazily evaluates the object you log. You could do a shallow clone of the event object to make console.log
work.
For debugging purposes,
console.shallowCloneLog = function(){
var typeString = Function.prototype.call.bind(Object.prototype.toString)
console.log.apply(console, Array.prototype.map.call(arguments, function(x){
switch (typeString(x).slice(8, -1)) {
case 'Number': case 'String': case 'Undefined': case 'Null': case 'Boolean': return x;
case 'Array': return x.slice();
default:
var out = Object.create(Object.getPrototypeOf(x));
out.constructor = x.constructor;
for (var key in x) {
out[key] = x[key];
}
Object.defineProperty(out, 'constructor', {value: x.constructor});
return out;
}
}));
}
console.shallowCloneLog(e)
Event handlers will be passed instances of SyntheticEvent
. The SyntheticEvent
is pooled. This means that the SyntheticEvent
object will be reused and all properties will be nullified after the event callback has been invoked.
If you want to access the event properties in an asynchronous way, you should call event.persist()
func(e){
e.persist();
console.log(e);// all the properties are retained
}
render () {
return(
<div onMouseOver={this.func}>
//rest of the logic
</div>
);
}