美文网首页
bind(this) 我的理解

bind(this) 我的理解

作者: 枫雪孤城 | 来源:发表于2018-11-23 05:41 被阅读83次

    普通函数中,内层函数不能从外层函数中继承this的值,在内层函数中,this会是window或者undefined(取决于是否使用严格模式),可以设置一个临时变量用来将外部的this值导入到内部函数中,再一个方法就是在内部函数执行.bind(this)。

    而箭头函数的this是继承父级的this。

    因此在React中要注意,在一个方法中调用this.setState()等函数,或者在render()方法中被调用,都有内层函数参与,因此需要将该方法的this绑定到class。所以如果是用function的普通方法定义,需要在constructor中bind(this),如:this.onChange = this.onChange.bind(this);
    这样this指向组件实例,就可以在render()中使用,也可以在方法中调用this.setState()方法了。

    或者直接用箭头函数进行定义。这样,this就继承自父级方法render(), 而render()的this为组件实例。

    这样一来,在render()中就可以愉快的使用了:

    render() {
    return(
    <input onChange={this.onChange}>
    );
    }

    不建议在render()中bind,如:<input onChange={this.onChange.bind(this)}>,因为它会在每次render()方法执行时绑定类方法,肯定对于性能有影响。而直接在constructor中bind, 则bind只会在组件实例化初时运行一次。

    相关文章

      网友评论

          本文标题:bind(this) 我的理解

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