记一次React中异步获取事件对象的爬坑经历

SyntheticEvent objects are pooled

在使用React过程中,直接异步获取事件对象上的属性,实际上我们拿到的值永远是null,下面的代码就存在问题

  const handleClick = e => {
        setTimeout(() => {
            console.log(e.target.name)
        });
    }

控制台会输出 null。出现上面这种情况,React官方给出的解释如下:

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 事件处理中,事件对象被包装在一个 SyntheticEvent(合成事件)对象中。这些对象是被池化的(pooled),这意味着在事件处理程序会把这些对象重用于其他事件以提高性能。随之而来的问题就是,异步访问事件对象的属性是不可能的,因为事件的属性由于重用而被重置(nullified)。

解决方式是把事件对象e 赋值到一个内部变量上。

  const handleClick = e => {
    let name = e.target.name;    //   将需要从事件对象上获取的信息,先缓存到变量上面
        setTimeout(() => {
            console.log(name);
        });
    }

React 官方实例

function onClick(event) {
  console.log(event); // => nullified object.
  console.log(event.type); // => "click"
  const eventType = event.type; // => "click"

  setTimeout(function() {
    console.log(event.type); // => null
    console.log(eventType); // => "click"
  }, 0);

  // Won't work. this.state.clickEvent will only contain null values.
  this.setState({clickEvent: event});

  // You can still export event properties.
  this.setState({eventType: event.type});
}

想异步访问事件属性,可以在事件上调用event.persist(),这会从池中移除合成事件并允许对事件的引用被保留。

猜你喜欢

转载自www.cnblogs.com/changlon/p/10155706.html
今日推荐