tengfeng 发表于 2018-9-18 23:01:29

React中constructor(props){}究竟是什么,以及super(props)与super()

本帖最后由 tengfeng 于 2018-9-18 23:11 编辑

在React Class中设置state的初始值或者绑定事件时

为什么需要在 constructor(){} 中加上 super() 呢

我们尝试去掉 super() 看看编译的结果:





提示没有在this之前加上super()其实就是少了super(),导致了this的 Reference Error
React中 super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
正确的姿势应该是这样


Es6中的super可以用在类的继承中,super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。



        class Person {
               constructor (name) {
                          this.name = name;
                }
        }

        class Student extends Person {
                constructor (name, age) {
                            super(); // 用在构造函数中,必须在使用this之前调用
                            this.age = age;
               }
        }


React中constructor(props){}究竟是什么,以及super(props)与super() 它们的区别在哪儿呢?What's the difference between “super()” and “super(props)” in React when using es6 classes?借用下stackoverflow上的解释There is only one reason when one needs to pass props to super():When you want to access this.props in constructor.(Which is probably redundant since you already have a reference to it.)意思是说:只有一个理由需要传递props作为super()的参数,那就是你需要在构造函数内使用this.props那官方提供学习的例子中都是写成super(props),所以说写成super(props)是完全没问题的,也建议就直接这样写




页: [1]
查看完整版本: React中constructor(props){}究竟是什么,以及super(props)与super()