什么是反应中的事件池? [英] What is event pooling in react?

查看:31
本文介绍了什么是反应中的事件池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SyntheticEvent 被合并.这意味着 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. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

参考:React 中的事件系统

推荐答案

表示事件的属性只在回调处于活动状态时存在.将异步添加到混合中,或存储事件以备将来使用,都将失败.

It means that the properties of the event only exist while the callback is active. Adding async to the mix, or storing the event for future use, will fail.

如果您在事件处理程序中尝试 console.log(event),这很容易观察到.当您检查对象时,事件对象上的大多数属性都将为 null.如果您在记录值后立即使用 debugger; 停止执行脚本,您可以检查这些值.

This is easily observed if you try console.log(event) inside an event handler. By the time you inspect the object, most properties on the event object will be null. If you stop execution of the script with debugger; immediately after logging the value, you can inspect the values.

class MyComponent extends React.Component {
    handleClick (e){
    console.log('The event currentTarget is', e.currentTarget); // DOM element
    setTimeout(() => {
    console.log('event.currentTarget was', e.currentTarget); // null
  }, 1000)
  }
  render () {
    return <button onClick={this.handleClick}>Fire event!</button>
  }
}

这将在您单击按钮时记录一个 DOM 元素,并在下一秒后记录 null.由于我不知道的原因,event.target 仍然存储到下一个事件发生之前,并且不会被取消.

This will log a DOM element when you click the button, and null a second later. For reasons beyond me, event.target is still stored until the next event occurs, and not nullified.

这篇关于什么是反应中的事件池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆