2016-01-21 44 views
6

的jsfiddle:https://jsfiddle.net/leiming/5e6rtgwd/的onfocus氣泡在陣營

class Sample extends React.Component { 
 

 
    onInputFocus(event) { 
 
    console.log('react input focus') 
 
    } 
 

 
    onSpanFocus(event) { 
 
    console.log('react span focus') 
 
     // event.stopPropagation() 
 
    } 
 

 
    render() { 
 
    return (<span onFocus = {this.onSpanFocus}> 
 
     react input: <input type="text" 
 
     onFocus = {this.onInputFocus} /> 
 
     </span>) 
 
    } 
 
} 
 

 
ReactDOM.render(< Sample/> , 
 
    document.getElementById('container') 
 
);
<div id="container"> 
 
    <!-- This element's contents will be replaced with your component. --> 
 
</div> 
 

 
<div> 
 
    <span onfocus="(function(){console.log('normal span')})()"> 
 
    normal input:<input type="text" onfocus="(function(){console.log('normal input focus')})()"> 
 
</span> 
 
</div>

的jsfiddle:https://jsfiddle.net/leiming/5e6rtgwd/

使用反應,onFocus<input/>將泡沫這是不平常一樣HTML5。

任何人都可以給我推薦文檔爲什麼集中泡泡與React?

+1

他們正在研究它:https://github.com/facebook/react/issues/6410 – velop

回答

12

focus事件do not bubble,所以你是正確的,React中的行爲與DOM的行爲不同。 DOM有focusin事件that does bubble;這裏有一個演示:通過the React source code

<div> 
 
    <span onfocus="(function(){console.log('span focus')})()"> 
 
    onfocus: <input type="text" 
 
       onfocus="(function(){console.log('input focus')})()"> 
 
    </span> 
 
</div> 
 

 
<div> 
 
    <span onfocusin="(function(){console.log('span focusin')})()"> 
 
    onfocusin: <input type="text" 
 
       onfocusin="(function(){console.log('input focusin')})()"> 
 
    </span> 
 
</div>

來看,似乎這是故意的;該代碼檢查瀏覽器是否支持focus事件並捕獲,並通過focus事件與ReactEventListener.trapCapturedEvent而不是ReactEventListener.trapBubbledEvent實現它。這是必要的,因爲React使用事件委託來實現其綜合事件系統,因此需要爲其所有事件處理使用捕獲或冒泡。 The article linked to in the comment解釋了這是如何工作的:

問題是這些事件不起泡。鏈接上的焦點或模糊事件僅在鏈接本身上激發,而不在鏈接的任何祖先元素上激發。

這是一個古老的規則。一些事件,尤其是焦點,模糊和變化,不會冒充文檔樹。確切的原因在歷史的迷霧中已經消失,但部分原因是這些事件對某些元素沒有意義。用戶無法以任何方式專注於或更改隨機段落,因此這些事件僅在這些HTML元素上不可用。另外,它們不會冒泡。

...

除了當您使用事件捕獲。

...

我的一個事件研究的最奇怪的結論之一是,當你在拍攝階段定義事件處理程序的瀏覽器中執行任何和事件目標是否祖先設置的所有事件處理程序給定的事件對這些元素是否有意義。

這似乎很可能是做出反應小組決定只是讓總是泡事件(其中,說實話,是我從DOM規範預期,以及直到我讀你的問題)。瀏覽器的實現似乎不一致; one issue comment提到focus事件在Firefox中冒泡,但我無法在最近的版本中重現該事件。但是,使用onfocusin屬性或使用addEventListener("focusin", ...)在FF中也不起作用。所以有可能這只是一個嘗試在瀏覽器中規範化事件。

所有這一切說,似乎有可能是上的.bubbles屬性是false而不是true

+0

謝謝,明確的解釋 –

+0

好的解釋,你真的努力瞭解並解釋清楚的信息辦法。 – alexrussell