React.js onClick事件返回所有空值

boo*_*oom 23 javascript reactjs

module.exports = React.createClass({
  click: function(e){
    console.log(e)
  },
  render: function() {
    return div({className: "thing1", children:[
      div({className: "thing2", onClick: this.click})
    ]})
  }
})
Run Code Online (Sandbox Code Playgroud)

传递给的事件包含所有单击对象的制作但值为null.

Object { dispatchConfig: null, dispatchMarker: null, nativeEvent: null, type: null, target: null, currentTarget: null, eventPhase: null, bubbles: null, cancelable: null, timeStamp: null, 22 more… }
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Bri*_*and 27

出于性能原因,对事件池进行反应.因此,它从池中获取一个事件对象,在其上设置属性,调用您的处理程序,然后将所有属性设置为null,以便可以重用它.

这主要是一个问题,因为console懒惰评估您记录的对象.您可以对事件对象进行浅层克隆以进行console.log工作.

出于调试目的,

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;
    }
  }));
}
Run Code Online (Sandbox Code Playgroud)
console.shallowCloneLog(e)
Run Code Online (Sandbox Code Playgroud)

  • 出于简单的调试目的,在记录事件之前调用事件上的`persist()`可能是一个很好的解决方法. (7认同)

San*_*eev 13

事件处理程序将被传递给实例SyntheticEvent.将SyntheticEvent被合并.这意味着在调用事件回调之后,SyntheticEvent将重用该对象并且所有属性都将无效.

如果要以异步方式访问事件属性,则应调用 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>
    );
}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您使用的是第 2 阶段或更高阶段的 ES6 功能,console.log({...e})则其工作方式与上面的浅层克隆实现相同。