New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[react] super()
和super(props)
有什么区别?
#898
Comments
super() 可以让我们使用this来调用各种东西, |
如果只调用了 class Button extends React.Component {
constructor(props) {
super(); // 没有传 props
console.log(props); // {}
console.log(this.props); // undefined
}
// ...
} |
react 中的class 是基于es6的规范实现的, 继承是使用extends关键字实现继承的,子类必须在constructor()中调用super() 方法否则新建实例 如果你使用了constructor就必须写super() 这个是用来初始化this的,可以绑定事件到this上 |
根据es6的规定,子类自己的构造函数中必须调用super,才能获得自己的this;所以只是super()的话,只能够让子类获取自己的this;但是props会是Undefined,如果传递了props给super,那么才会初始化子类自己的props |
es6规定了子类中如果使用constructor构造函数,在super调用之前是没有自己的this,调用super用来初始化子类的this,至于在super中传props是为了可以通过this.props的形式访问父组件传过来的props |
[react]
super()
和super(props)
有什么区别?The text was updated successfully, but these errors were encountered: