栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么我必须对React组件类中定义的方法进行.bind(this),而在常规ES6类中却不必

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么我必须对React组件类中定义的方法进行.bind(this),而在常规ES6类中却不必

组件中的事件处理程序不会像其他方法(生命周期方法…)那样自动绑定到组件实例。

class MyComponent extends React.Component {   render(){      return (         <div onClick={this.renderElements}>  {this.renderElements()} <-- `this` is still in side the MyComponent context         </div>      )   }}//under the hoodvar instance = new MyComponent();var element = instance.render();//click on divelement.onClick() <-- `this` inside renderElements refers to the window object now

查看此示例以了解

this
更多信息:

class Animal {     constructor(name) {        this.name = name;    }    speak() {        console.log(this.name + ' makes a noise.');    }  }class Dog extends Animal {    run(){       console.log(this.name + ' runs');    }    speak() {        console.log(this.name + ' barks.');        this.run(); <-- `this` is still in the Dog context        return {onRun : this.run};    }}var d = new Dog('Mitzie');var myDog = d.speak();myDog.onRun() <-- `this` is now in the global context which is the `window` object

您可以查看本文以获取更多信息。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号