马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
在学习React中的class组件时,先巩固一下ES6中class语法和继承原理,背面先容怎样基于extends实现继承。
class语法
静态属性和方法是属于类本身的,而不是类的实例对象。静态成员通常用于形貌类的特性或功能,而不是形貌某个具体实例的状态。它们是通过 class 关键字直接界说在类上,而不是通过 constructor 或实例方法界说。实例对象的·__proto__(原型链)会指向类的原型对象(Parent.prototype),但静态成员 不 会出如今实例对象或其原型链中。静态成员只能通过类本身来访问,而不能通过实例来访问。
- class Parent{
- // new的时候,执行的构造函数「可写可补血,需要接受传递尽量的实参信息,才需要设置constructor」
- constructor(x,y){
- // this-> 创建的实例
- // 创建私有属性total
- this.total = x+y;
- }
- num = 200;// 等价于this.num=2000;
- getNum=()=>{//添加私有属性getNum
- //箭头函数没有自己的this,所用到的this是宿主函数中的
- console.log(this);
- }
- sum(){
- //类似sum= function(){}不是箭头函数
- //它是给Parent.prototype上设置公共方法「sum不是可枚举的」
- }
- static avg = 10000;
- //把构造函数当作一个普通对象,为其设置静态的私有属性方法 ,Parent.average
- static average(){}
- }
- let p = new Parent();
- console.log(p,'p')
- console.dir(Parent,'Parent')
复制代码- 访问类的静态属性
- console.log(Parent.avg); // 10000
- Parent.average(); // 调用静态方法
复制代码 实例p打印如下:
Parent打印如下
基于extends实现继承
- class Parent extends React.Component{
- constructor(props){
- super(props);//继承 React.Component 构造器,初始化 props
- }
- x=100;
- getX(){ }
- }
- let p = new Parent(10);
- console.log(p)
复制代码 1、起首基于call继承 React.Component.call(this),此中this-> arent类的实例p,给创建的实例p设置四个私有属性:props、context、refs、updater
Component 的源码如下:
- function Component(props,context,updater){
- this.props = props; // 存储传入的 props(组件的属性)
- this.context = context; // 存储上下文对象(用于跨组件传递数据)
- this.refs = emptyObject; // 存储组件引用,用于获取子组件实例或 DOM 节点
- this.updater = updater || ReactNoopUpdateQueue;//ReactNoopUpdateQueue,这是一个默认的更新队列,用于在 React 中触发组件更新。
- }
复制代码 2、再基于原型继承Parent.prototype._proto_ === React.Component.prototype
通过 call 继承完成初始化之后,实例的__proto__会指向 Parent.prototype,同时 Parent.prototype 的 __proto__ 会指向 React.Component.prototype,还备React.Component.prototype原型上提供的方法(isReactComponent、setState、forceUpdate),原型链的指向:实例-> Parent.prototype->React.Component.prototype->Object.pototype;
3、只要设置了 constructor,则内部第一句话肯定要实行super()
- super(props) 会调用父类(React.Component)的构造函数,确保父类的初始化逻辑(即 React.Component.call(this))被实行,同时将 props 转达给父类的构造函数。
- 如果没有界说 constructor,JavaScript 会主动提供一个默认的构造函数,它会隐式调用 super()。
- class Parent extends React.Component{
- // constructor(n,m){
- // 调用父类(React.Component)的构造函数
-
- // super() //=>React.Component.call(this),此时this.props=undefined,this.context=undefined this.refs={}
-
- // // super(10) 此时this.props = 10;
-
- // }
- constructor(props){
- //确保父类构造函数被调用,this.props 会被正确初始化
- super(props);
- }
- x=100;
- getX(){ }
- }
- let p = new Parent(10);
- console.log(p)
复制代码 总结一下:
- 继承的实现:通过 extends React.Component,子类 Parent 继承了 React.Component,而且拥有了 React.Component 中界说的全部生命周期方法(如 componentDidMount、render 等)以及 setState、forceUpdate 等方法。
- 调用 super(props):在子类 Parent 的构造函数中,super(props) 调用了 React.Component 的构造函数,使得 this.props 得到正确初始化。这个步调是必须的,由于没有它,this.props 会是 undefined。
- 原型链:当 Parent 类实例化时,它会继承 React.Component.prototype 上的全部方法。原型链结构是:实例 -> Parent.prototype -> React.Component.prototype -> Object.prototype。
|