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

chore: compatible for React16 #436

Merged
merged 4 commits into from
Nov 6, 2023
Merged

chore: compatible for React16 #436

merged 4 commits into from
Nov 6, 2023

Conversation

zombieJ
Copy link
Member

@zombieJ zombieJ commented Nov 3, 2023

背景

ant-design/ant-design#45653 的 PR 中,为组件添加 autoFocus 事件导致在 React 16 的 test case 中不会触发 onFocus 事件。

问题由来

为错误打 console 可以发现,React 内部已经触发了 react-focus 事件。问题是 React 16 没有把这个事件正确触发。

截屏2023-11-03 23 12 59

错误信息来自于 rc-trigger 调用了 flushSync 导致生命周期报错。

相关部分

rc-slider

autoFocus 属性会通过 useEffect 触发 handleRef.current.focus 方法触发聚焦。

rc-trigger

rc-triggeraction 标记为 focus 的事件添加监听事件,并且触发对应的 triggerOpen 逻辑。

#415 中,rc-trigger 为支持 disabled 元素也能触发 open 而同时兼容旧版不支持 pointerEvent 浏览器所以同时保留了 mouseEvent 监听。所以当元素被悬浮时,会触发 onPointerEnteronMouseEnter 事件。

而在 React 18 中,这两个事件会被 batch update。导致通过 open 是否变化来判断要触发 onOpenChange 的事件因为闭包问题导致会触发两次。所以在 #415 中,使用了 flushSync 确保两个事件之间不被 batch update 掉。

报错原因

useEffect 中触发的 focus 事件调用 focus 并触发 rc-triggertriggerOpen 方法后调用 flushSync 事件。在 React 16 中,useEffect 被视为生命周期进行中,导致在此不允许调用 flushSync。而在 React 18,useEffect 中不再视为上一个 render 的生命周期,因而 focus 事件触发的 flushSync 不会出现 flushSync was called from inside a lifecycle method 错误。

解决方案

使用 useRef 记录最后触发的 open 状态,如果相同就不再触发。该 ref 每次 render 都会被重置。

Copy link

codecov bot commented Nov 3, 2023

Codecov Report

Merging #436 (f90eb56) into master (4f736dd) will increase coverage by 0.01%.
The diff coverage is 100.00%.

❗ Current head f90eb56 differs from pull request most recent head b6ca1c1. Consider uploading reports for the commit b6ca1c1 to get more accurate results

@@            Coverage Diff             @@
##           master     #436      +/-   ##
==========================================
+ Coverage   97.72%   97.73%   +0.01%     
==========================================
  Files          13       13              
  Lines         790      794       +4     
  Branches      231      224       -7     
==========================================
+ Hits          772      776       +4     
  Misses         18       18              
Files Coverage Δ
src/index.tsx 97.00% <100.00%> (+0.06%) ⬆️

📣 Codecov offers a browser extension for seamless coverage viewing on GitHub. Try it in Chrome or Firefox today!

@zombieJ zombieJ merged commit 6b09c6f into master Nov 6, 2023
7 checks passed
@zombieJ zombieJ deleted the for-16 branch November 6, 2023 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants