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/
在< input />中使用React,onFocus泡泡与通常的HTML5不一样.
任何人都可以给我推荐文件为什么用React集中泡泡?
解决方法
<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>
看看the React source code,看来这是故意的;代码检查浏览器是否支持捕获焦点事件,并通过焦点事件使用ReactEventListener.trapCapturedEvent而不是ReactEventListener.trapBubbledEvent来实现它.这是必要的,因为React使用事件委托来实现其合成事件系统,因此需要使用捕获或冒泡来进行所有事件处理. The article linked to in the comment解释了这是如何工作的:
The problem is that these events do not bubble up. A focus or blur event on a link fires only on the link itself,and not on any ancestor element of the link.
This is an ancient rule. A few events,most notably focus,blur,and change,do not bubble up the document tree. The exact reasons for this have been lost in the mist of history,but part of the cause is that these events just don’t make sense on some elements. The user cannot focus on or change a random paragraph in any way,and therefore these events are just not available on these HTML elements. In addition,they do not bubble up.
…
Except when you use event capturing.
…
One of the most curIoUs conclusions of my event research is that when you define event handlers in the capturing phase the browser executes any and all event handlers set on ancestors of the event target whether the given event makes sense on these elements or not.
似乎很可能React团队决定简单地让事件始终冒泡(说实话,这也是我对DOM规范的期望,直到我读到你的问题).浏览器实现似乎不一致; one issue comment提到重点事件在Firefox中出现泡沫,但我无法在最近的版本中重现这一点.但是,使用onfocusin属性或使用addEventListener(“focusin”,…)在FF中也不起作用.因此,这可能只是尝试在浏览器之间规范化事件.
所有这一切,似乎确实存在一个错误,其中SyntheticFocusEvent上的.bubbles属性为false而不是true.