美文网首页
this指向以及react中绑定this

this指向以及react中绑定this

作者: 琴先森的博客 | 来源:发表于2019-06-21 17:54 被阅读0次
JavaScript函数中的this
  • 我们都知道JavaScript函数中的this不是在函数声明的时候定义的,而是函数调用(即运行)的时候定义的,this对象是运行时基于函数的执行环境(也就是上下文)绑定的。
var student = {
     func:function(){
          console.log(this)
     }
}

student.func();  // 打印了student对象,因为此时this指向student对象
var studentFunc = student.func;
studentFunc();  // 打印了window,因为此时是window调用的,this指向window
es6中class的this的指向
class Logger{
    printName(){
          this.print(`Hello ${name}`);
    }
    print(text){
        console.log(text);
    }
}

const logger = new Logger();
const {printName} = logger;
printName(); 

上述代码中,printName方法中的this默认指向Logger类的实例。但是如果将这个方法提取出来单独使用,this指向该方法运行时所在的环境(由于class内部是严格模式,所以this实际指向的是undefined),从而导致找不到print方法而报错。
一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print方法了。

constructor() {
      this.printName = this.printName.bind(this)
}

另一种解决方法是使用箭头函数。箭头函数内部的this总是指向定义时所在的对象。

React中绑定this
class LikeButton extends React.Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
  }
  render() {
    return (
      <div onClick={this.handleClick}>
      </div>
    );
  }
}
  • 在原来React.createClass中,handleClick() 在onClick事件触发的时候,会自动绑定到LikeButton实例上
  • 在ES6的class的写法中,Facebook取消了自动绑定。因为render多次调用每次都要bind会影响性能,对此我们有如下几种解决方案

使用bind()绑定的方法

\color{#f00}{直接bind * this型/constructor手动bind型}

  • 传参:
    第一个参数指向this,第二个参数开始才是事件函数接收到的参数
    事件对象e以及更多的参数将会被隐式的进行传递
    在类组件中定义的监听函数,事件对象e要排在所传递参数的后面
class Hello extends React.Component{
    constructor(){
        super()
        this.state = {
            content:true
        }
        this.change = this.change.bind(this,this.state.content) // 1.可以在constructor中绑定this
    }
    
    change(obj,e){ // 事件对象e被隐式传递并排在所传递参数的后面
      
    }

    render(){
        return (
            <div>
                <button onClick={this.change}>    {/*2.也可在具体使用该函数的时候绑定this.change.bind(this,this.state.content)*/}
                    点击
                </button>
            </div>
        )
    }
}

使用属性初始化器语法(还处于实验阶段)

class LoggingButton extends React.Component {
  // 这个语法确保了 `this` 绑定在  handleClick 中
  // 这里只是一个测试
  handleClick = () => {   // 传参的写法 andleClick = (params)
    console.log('this is:', this);
  }
 
  render() {
    return (
      <button onClick={this.handleClick}>   {/*传参的写法:onClick={this.handleClick(params)}*/}
        Click me
      </button>
    );
  }


}

在回调函数中使用箭头函数

  • 传参时,事件对象e必须进行显示的传递
  • 将函数的this绑定到其定义时所在的上下文
class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }
 
  render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中
    return (
      <button onClick={(e) => this.handleClick(e)}>  {/* 事件对象e必须进行显示的传递 */}
        Click me
      </button>
    );
  }
}
  • 弊端:每次LoggingButton渲染的时候都会创建一个\color{#FF0000}{不同}的回调函数。如果这个回调函数作为一个属性值传入低阶组件,这些组件可能会进行额外的渲染。所以建议在\color{#FF0000}{构造函数中绑定}或使用\color{#FF0000}{属性初始化器}语法来避免这类性能问题。

为什么使用bind而不是call和apply

  • 因为call和apply,都是立即就调用了对应的函数,而bind是返回一个函数,在调用的时候执行,传参方式跟call一样。

相关文章

  • this指向以及react中绑定this

    JavaScript函数中的this 我们都知道JavaScript函数中的this不是在函数声明的时候定义的,而...

  • react 备注

    1. React组件中绑定this 由于在JSX中的this不会指向当前对象,所以需要通过bind 参考文章: [...

  • 关于在React-Native中,使用ScrollView组件时

    在React-Native(以下简称RN)中,使用ScrollView组件时,绑定事件时this的指向会出现一些问...

  • react事件、生命周期

    事件 react中、原生事件绑定丢失this,绑定this写法 jsx中onClosed={ this.handl...

  • 学习react总结知识点

    传统HTML中 handleclick函数自动绑定了this,而react中 需要手动绑定,下面是回调函数绑定...

  • this 指针

    默认绑定 默认绑定 this 指向 window 严格模式 this 指向 undefined 隐式绑定 谁调用 ...

  • react中绑定this

    在开发过程中,react定义的组件中,如果不为事件处理程序绑定this: 当我点击按钮,页面将报错,我将this打...

  • react中的this

    在ES6写法中的react:React.Component创建组件,其成员不会自动绑定this,需要手动绑定。手动...

  • JavaScript中的this指向

    在全局中使用 this指向Window 函数中的this 谁调用函数指向谁 这里指向Window 事件绑定中的th...

  • this指向以及作用域和闭包

    一、关于this指向的几种场景 1、默认绑定(函数直接调用) 非严格模式下,默认绑定指向全局(node 中是 gl...

网友评论

      本文标题:this指向以及react中绑定this

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