Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 中的事件 #17

Open
negativeentropy9 opened this issue Aug 13, 2019 · 0 comments
Open

React 中的事件 #17

negativeentropy9 opened this issue Aug 13, 2019 · 0 comments

Comments

@negativeentropy9
Copy link
Owner

negativeentropy9 commented Aug 13, 2019

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.

codesandbox demo

测试效果

synthetic-event

总结

  • 不要在事件回调的 异步处理中访问 event 对象,此时 event 对象已经被重用,所有属性被清空,包括 targettype 等,如果一定要在异步处理访问跟 event 相关的属性,可以借助于闭包,在异步处理外面把要访问的属性缓存起来

  • setState 如果采用回调方式更新,那么跟异步处理一样,setState 只是一个绑定,而真正执行时才会访问 event 对象;如果采用对象方式更新,可以直接绑定其属性。

参考

Event Pooling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant