React focus 事件的坑

React 的 focus 事件實現有問題

  1. React 的 focus 事件會冒泡,可是原生 DOM 的 focus 事件是不冒泡的;
  2. 原生 DOM 的 focusin 事件是會冒泡的,可是如今 React 沒實現 focusin 事件;
  3. 因此如今根據 React 的 focus 事件的行爲,它應該被叫作 focusin 纔對。

能夠看這個 demojavascript

另外能夠發現 React 合成事件裏的 eventPhase 也是錯誤的。java

相關 issue:react

  1. Synthetic eventPhase doesn't reflect the synthetic phase
  2. onFocusIn/onFocusOut events

用 enzyme 寫測試的時候直接調用 input.focus() 不會觸發事件

緣由是 React 的合成事件是經過捕獲 document 上的事件實現的,可是由於 enzyme 的 mount 方法不會把建立的 div 掛到 body 上,因此直接在 DOM 元素上觸發事件 React 會捕獲不到。git

繞過方法是本身建立一個 div 掛到 body 上。github

const container = global.document.createElement('div');
global.document.body.appendChild(container);

mount(<App />, { attachTo: container });
相關文章
相關標籤/搜索