浅析React之事件系统(二)

上篇文章中,我们谈到了React事件系统的实现方式,和在React中使用原生事件的方法,那么这篇文章我们来继续分析下,看看React中合成事件和原生事件混用的各种情况。

上一个例子

在上篇文章中,我们举了个例子。为了防止大家不记得,我们来看看那个例子的代码。

class App extends React.Component {

  constructor(props){
    super(props);
    
    this.state = {
      show: false
    }
    
    this.handleClick = this.handleClick.bind(this)
    this.handleClickImage = this.handleClickImage.bind(this);
  }
  
  handleClick(){
   this.setState({
     show: true
   })
  }
  
  componentDidMount(){
    document.body.addEventListener('click', e=> {
      this.setState({
        show: false
      })
    })
  }
  
  componentWillUnmount(){
    document.body.removeEventListener('click');
  }
  
  handleClickImage(e){
    console.log('in this ')
    e.stopPropagation();
  }
  
  render(){
    return (
      <div className="container">
        <button onClick={this.handleClick}>Open Image</button>
          <div className="img-container" style={{ display: this.state.show ? 'block': 'none'}} onClick={this.handleClickImage}>
            ![](http://upload-images.jianshu.io/upload_images/65230-3ad92c3b2a23e6b5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
          </div>
      </div>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('root'));

这有什么问题呢? 问题就在于,如果我们点击image的内部依旧可以收起Image,那么这是为什么呢?这是因为我们及时点击了Image的内部,body上绑定的事件处理器依旧会执行,这样就让我们的image收起来了。那我们如果不想让image收起来改怎么做呢?

首先的想法是停止冒泡,如果我们在img-container中就停止冒泡了是不是就可以让image不消失了呢?比如这样:

...
handleClickImage(e){
    e.preventDefault();
    e.stopPropagation();
  }
  
  render(){
    return (
      <div className="container">
        <button onClick={this.handleClick}>Open Image</button>
          <div className="img-container" style={{ display: this.state.show ? 'block': 'none'}} onClick={this.handleClickImage}>
            ![](http://upload-images.jianshu.io/upload_images/65230-3ad92c3b2a23e6b5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
          </div>
      </div>
    )
  }
...

Open In CodePen

在这里我们定义一个handleClickImage的方法,在其中我们执行取消默认行为和停止冒泡。那是似乎效果并不是我们想要的。因为阻止React事件冒泡的行为只能用于React合成事件中,没法阻止原生事件的冒泡。同样用React.NativeEvent.stopPropagation()也是无法阻止冒泡的。

如何解决这样的问题呢?首先,尽量的避免混用合成事件和原生事件。需要注意的点是:

  1. 阻止react 合成事件冒泡并不会阻止原生时间的冒泡,从上边的例子我们已经看到了,及时使用stopPropagation也是无法阻止原生时间的冒泡的。
  2. 第二点需要注意的是,取消原生时间的冒泡会同时取消React Event。并且原生事件的冒泡在react event的触发和冒泡之前。同时React Event的创建和冒泡是在原生事件冒泡到最顶层的component之后的。我们来看这个例子:
class App extends React.Component {
  
  render(){
   return <GrandPa />;
  }
}

class GrandPa extends React.Component {
  constructor(props){
      super(props);
      this.state = {clickTime: 0};
      this.handleClick = this.handleClick.bind(this);
  }
  
 handleClick(){
   console.log('React Event grandpa is fired');
  this.setState({clickTime: new Date().getTime()})
};
  
  componentDidMount(){
    document.getElementById('grandpa').addEventListener('click',function(e){
      console.log('native Event GrandPa is fired');
    })
  }
  
  render(){
    return (
      <div id='grandpa' onClick={this.handleClick}>
        <p>GrandPa Clicked at: {this.state.clickTime}</p>
        <Dad />
      </div>
    )
  }
}

class Dad extends React.Component {
  constructor(props){
    super(props);
    this.state = {clickTime:0};
    this.handleClick=this.handleClick.bind(this);
  }
  
  componentDidMount(){
    document.getElementById('dad').addEventListener('click',function(e){
      console.log('native Event Dad is fired');
      e.stopPropagation();
    })
  }
  
  handleClick(){
    console.log('React Event Dad is fired')
    this.setState({clickTime: new Date().getTime()})
  }
  
  render(){
    return (
      <div id='dad' onClick={this.handleClick}>
       <p>Dad Clicked at: {this.state.clickTime}</p>
        <Son />
      </div>
     )
  }
}

class Son extends React.Component {
  constructor(props){
    super(props);
    this.state = {clickTime:0};
    this.handleClick=this.handleClick.bind(this);
  }
  
  handleClick(){
    console.log('React Event Son is fired');
    this.setState({clickTime: new Date().getTime()})
  }
  
  componentDidMount(){
    document.getElementById('son').addEventListener('click',function(e){
      console.log('native Event son is fired');
    })
  }
  
  render(){
    return (
      <div id="son">
       <p onClick={this.handleClick}>Son Clicked at: {this.state.clickTime} </p>
      </div>
     )
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

Open in CodePen

在这个例子中我们有三个component,Son Dad,Grandpa。同时定义了React Event handler 和 native event handler,并在Dad的native Event handler中stopPropagation,当我们点击Son or Dad component的时候会发现,React Event handler并没有被trigger。
console里的output为:

"native Event son is fired"
"native Event Dad is fired"

这就说明native Event的停止冒泡可以阻断所有的React Event。所以即使我们是在Dad上停止冒泡的,依旧阻断了Son上的React Event。

同时如果我们把dad上的stopPropagation remove掉我们会看到如下结果:

"native Event son is fired"
"native Event Dad is fired"
"native Event GrandPa is fired"
"React Event Son is fired"
"React Event Dad is fired"
"React Event grandpa is fired"

这就说明React的合成时间是在原生事件冒泡到最顶层组件结束后才创建和冒泡的,也是符合React的原理,因为在是实现的时候React只是将一个Event listener 挂在了最顶层的组件上,其内部一套自己的机制进行事件的管理。

浅析React之事件系统(一)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容