简述RN组件constructor(){} 中加上 super()的作用

首先通过下述例子了解在es6中实现继承:

class father{
    constructor(name) {
         this.name = name
    }
    
    printName() {
        console.log(this.name)
    }
}


class children extends father{
    constructor(name,age) {
        super(name) // super代表的是父类的构造函数
        this.age = age
    }

    printAge() {
        console.log(this.age)
    }
}

let jack = new children('jack',20)
    jack.printName()    //输出 : jack
    jack.printAge()    //输出 : 20

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

根据以下三个总结可以快速理解:

  1. 如果你用到了constructor就必须写super(),是用来初始化this的,可以绑定事件到this上;
  2. 如果你在constructor中要使用this.props,就必须给super加参数:super(props) ;
  3. 如果没用到constructor,在render中this.props都是可以使用的,这是React自动附带的。附上如下代码理解:
class HelloMessage extends React.Component{
    render (){
        return (
            <View>
                <Text>nice to meet you! {this.props.name}</Text>
            </View>
        );
    }
}
//不过这种只是用render的情况,使用一般的ES6函数写会更简便:
const HelloMessage = (props)=>(
    <View>
       <Text>nice to meet you! {this.props.name}</Text>
    </View>
)

END

发布了36 篇原创文章 · 获赞 64 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/u010379595/article/details/82393021