在本教程中,涵盖了React类构造函数中super和super with props参数之间的区别。
例如,React组件在构造函数中被定义为super(props)。
class PropsExampleComponent extends React.Component {
constructor(props) {
super(props);
}
}
在这个组件中,super与props被定义在一个类的构造函数中。
class ExampleComponent extends React.Component {
constructor(props) {
super();
}
}
让我们解释一下这两个组件的区别和它的不同之处。
Super是javascript中的一个关键字,用于在hirearcy中调用超级或父类 React类用ES6语法扩展React.Component
在ES6中,类使用extends 关键字扩展其他类。扩展允许我们在子类中使用父类数据。
class Animal {
constructor(type) {
this.type = type;
}
}
class Lion extends Animal {
constructor(type) {
super(type);
}
eat() {
console.log('Lion eat'+this.type);
}
}
重要的规则是eat方法只在超级类型的值被初始化后被调用,那么超级类的type value 。使用this ,我们可以调用this.eat方法来执行eat函数。
在使用extend关键字时,this和super有一个ES6的限制
-
在调用super关键字之前,子类不能使用这个关键字。
-
如果类扩展了其他类,子类的构造函数必须使用super作为构造函数的第一行。
结论是,extends类总是在调用这个关键字之前调用super关键字。
这条规则同样适用于React组件。
反应构造函数中的超级与超级道具
Super 用于访问父类的方法和数据super(props) 将初始化父类的props数据, this.props子组件就可以使用了。
如果组件在构造函数中没有定义超级,会发生什么?
class ExampleComponent extends React.Component {
constructor(props) {
console.log(this); // an error
}
}
上面的代码会产生以下错误,因为this 不会在超级构造函数之前被调用。
ReferenceError。在访问'this'或从派生构造函数返回之前,必须调用派生类中的超级构造函数。
class ExampleComponent extends React.Component {
constructor(props) {
super();
console.log(this); // ExampleComponent{props: undefined, context: undefined, refs: {…}, updater: {…}}
}
}
接下来在构造函数中访问this.props而不调用super
class ExampleComponent extends React.Component {
constructor(props) {
super();
console.log(this.props); // undefined
}
}
如果我们使用props而不是this.props,这也是可行的
class ExampleComponent extends React.Component {
constructor(props) {
super();
console.log(props); // this works and gives an array
}
}
This.props在调用super时给出了未定义。
所以,现在this.props在调用super(props)后给出了一个预期值。
class ExampleComponent extends React.Component {
constructor(props) {
super(props);
console.log(this.props); // gives prints the properties array
}
}
总结
在访问子组件中的任何方法或数据之前,super是构造函数中的第一条语句,使用这个语句,this.props返回未定义,为了使其成为this.props,你必须在子类构造函数的第一行调用super(props)。