Skip to main content

React 合成事件和原生事件的区别?

· 4 min read
hbGEf5

React v17 新变化

  • onScroll Bubbling Event: In React previous version there was a lesser known bug , the parent element used to capture the scroll event of the children this was causing an issue in using the scroll event listener, this has been fixed now

  • No Event Pooling: For those who don't know what Event Pooling is: The event handlers that we have in any react-app are actually passed instances of SyntheticEvent(A Wrapper for native browser events so that they have consistent properties across different browsers).

    Whenever an event is triggered, it takes an instance from the pool and populates its properties and reuses it. When the event handler has finished running, all properties will be nullified and the synthetic event instance is released back into the pool.

    This was build to actually increase the performance but It didn't improve the performance in the modern browsers and also it used to confuse the developers so they decided to remove it.

React v16 事件池

SyntheticEvent 对象会被放入池中统一管理。这意味着 SyntheticEvent 对象可以被复用,当所有事件处理函数被调用之后,其所有属性都会被置空。例如,以下代码是无效的:

function handleChange(e) {
// This won't work because the event object gets reused.
setTimeout(() => {
console.log(e.target.value); // Too late!
}, 100);
}

如果你需要在事件处理函数运行之后获取事件对象的属性,你需要调用 e.persist()

function handleChange(e) {
// Prevents React from resetting its properties:
e.persist();

setTimeout(() => {
console.log(e.target.value); // Works
}, 100);
}

React v17 去除事件池

React 17 中移除了 “event pooling(事件池)“。它并不会提高现代浏览器的性能,甚至还会使经验丰富的开发者一头雾水:

function handleChange(e) {
setData(data => ({
...data,
// This crashes in React 16 and earlier:
text: e.target.value,
}));
}

这是因为 React 在旧浏览器中重用了不同事件的事件对象,以提高性能,并将所有事件字段在它们之前设置为 null。在 React 16 及更早版本中,使用者必须调用 e.persist() 才能正确的使用该事件,或者正确读取需要的属性。

React 17 中,此代码可以按照预期效果执行。旧的事件池优化操作已被完成删除,因此,使用者可以在需要时读取事件字段

这改变了行为,因此我们将其标记为重大更改,但在实践中我们没有看到它在 Facebook 上造成影响。(甚至还修复了一些错误!)请注意,e.persist() 在 React 事件对象中仍然可用,只是无效果罢了。

参考资料

  1. React v16 事件池
  2. React v17.0 RC 版本发布:没有新特性
  3. React 17 : Why it's so important ?