• React事件绑定的几种方式对比


    React事件绑定

    由于类的方法默认不会绑定this,因此在调用的时候如果忘记绑定,this的值将会是undefined。
    通常如果不是直接调用,应该为方法绑定this。绑定方式有以下几种:

    1. 在构造函数中使用bind绑定this

    
    class Button extends React.Component {
    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
      }
      handleClick(){
        console.log('this is:', this);
      }
      render() {
        return (
          <button onClick={this.handleClick}>
            Click me
          </button>
        );
      }
    }
    

    2. 在调用的时候使用bind绑定this

    
    class Button extends React.Component {
      handleClick(){
        console.log('this is:', this);
      }
      render() {
        return (
          <button onClick={this.handleClick.bind(this)}>
            Click me
          </button>
        );
      }
    }
    

    3. 在调用的时候使用箭头函数绑定this

    
    class Button extends React.Component {
      handleClick(){
        console.log('this is:', this);
      }
      render() {
        return (
          <button onClick={()=>this.handleClick()}>
            Click me
          </button>
        );
      }
    }
    

    4. 使用属性初始化器语法绑定this(实验性)

    
    class Button extends React.Component {
      handleClick=()=>{
        console.log('this is:', this);
      }
      render() {
        return (
          <button onClick={this.handleClick}>
            Click me
          </button>
        );
      }
    }
    

    比较

    方式2方式3都是在调用的时候再绑定this。

    • 优点:写法比较简单,当组件中没有state的时候就不需要添加类构造函数来绑定this
    • 缺点:每一次调用的时候都会生成一个新的方法实例,因此对性能有影响,并且当这个函数作为属性值传入低阶组件的时候,这些组件可能会进行额外的重新渲染,因为每一次都是新的方法实例作为的新的属性传递。

    方式1在类构造函数中绑定this,调用的时候不需要再绑定

    • 优点:只会生成一个方法实例,并且绑定一次之后如果多次用到这个方法也不需要再绑定。
    • 缺点:即使不用到state,也需要添加类构造函数来绑定this,代码量多一点。。。

    方式4:利用属性初始化语法,将方法初始化为箭头函数,因此在创建函数的时候就绑定了this。
    优点:创建方法就绑定this,不需要在类构造函数中绑定,调用的时候不需要再作绑定。结合了方式1方式2方式3的优点
    缺点:目前仍然是实验性语法,需要用babel转译

    总结

    方式1是官方推荐的绑定方式,也是性能最好的方式。方式2和方式3会有性能影响并且当方法作为属性传递给子组件的时候会引起重渲问题。方式4目前属于实验性语法,但是是最好的绑定方式,需要结合bable转译

    来源:https://segmentfault.com/a/1190000011317515

  • 相关阅读:
    python增量爬虫pyspider
    python进程池:multiprocessing.pool
    1. 装饰器入门
    python绘图:matplotlib和pandas的应用
    高效使用 Python 可视化工具 Matplotlib
    python制作爬虫爬取京东商品评论教程
    python 爬取天猫美的评论数据
    mysql view
    mysql alter使用
    export和export default
  • 原文地址:https://www.cnblogs.com/datiangou/p/10161746.html
Copyright © 2020-2023  润新知