作者: shanshanfei | 来源:发表于2021-07-19 19:49 被阅读0次
    1. react中事件绑定的几种方式
    ① render中用bind:<Button onClick={this.onHandle.bind(this)}></Button>
    ② constructor中用bind:this.onHandle = this.onHandle.bind(this);
    ③ render中用箭头函数:<Button onClick={() => { this.onHandle(); }}></Button>
    ④ 函数定义时就用箭头函数,直接绑定this实例:onHandle = () => {...}
    
    对比:第1和3虽然写法简单,但是每次渲染都会重新绑定、生成新的匿名函数,有一定的性能开销,而且作为props传给子组件时,因为是新的值,还会导致子组件的重新渲染;第2种就是写法麻烦,多写代码;综合下来,最常用的就是第4种了。
    

    相关文章

      网友评论

          本文标题:

          本文链接:https://www.haomeiwen.com/subject/cfwhmltx.html