super(props)与react类式组件

1 为什么super()

super是对父类构造器的调用。使用了后会自动继承父类的属性。要把super()放到第一行是因为了以防在super()之前,也就是没实例化父类之前,访问父类的属性。所以js将此作为一个语法点,必须这么写
在这里插入图片描述

2、为什么super(props)加props

如果不加props,又调用了父类的构造器,就没把属性值传给父类啊! 父类的属性都是undefined

class Fa {
  name;
  age;
  constructor(props: { name: string; age?: number }) {
    this.name = props.name;
    this.age = props.age || 100;
  }
 }
class Son extends Fa {
  color;
  constructor(props: { name: string; age?: number; color: string }) {
    super();
    this.color = props.color;
  }
}
const son = new Son({xxxx})

就会报错如下:
在这里插入图片描述

网上看到很多回答 说是:不加props 构造器里没法访问 this.props。我试了根本不是这样。而是直接报错如上图。props并不是类的一个 关键字!!所以 如果 父类、或子类 没有定义props属性。就根本没法 访问 this.props

在这里插入图片描述

————————

补充:
为什么很多资料都有如上图所示的回答 是因为,在react的Component类里对props就默认是从上层组件传过来的 参数。再react里默认props就是用来传参的方式。所以可以理解为this.props是react类组件必备的一个东西。普通的类是不必须需要的。

React Componet 的构造函数

我们可以理解为 react 里对 props做了类似class Fa 的 下述处理(注意看注释)

class Fa {
  name;
  age;
  props: any;//只有这里声明了  props  
  constructor(props: { name: string; age?: number }) {
    this.name = props.name;
    this.age = props.age || 100;
    this.props = props;//这里给props赋值  下面才能用
  }

  getName() {
    return this.name;
  }

  static staticFun() {
    console.log("FA config ing");
  }
}
Fa.staticFun();

const fa0 = new Fa({ name: "M" });
console.log("fa0.name", fa0.name);
console.log("fa0.fun", fa0.getName());

class Son extends Fa {
  color;
  constructor(props: { name: string; age?: number; color: string }) {
    super(props);
    this.color = props.color;
    console.log("this.props", this.props);//这里才能用
  }

  logThis() {
    console.log("this.props", this.props);//这里才能用
    console.log("this", this); 
  }
}

const son0 = new Son({ name: "YANG", age: 10, color: "YELLOW" });
console.log("son0", son0);
console.log("son0.color", son0.color);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值