Skip to content
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

Open
haizhilin2013 opened this issue Jul 16, 2019 · 6 comments
Open

[react] super()super(props)有什么区别? #898

haizhilin2013 opened this issue Jul 16, 2019 · 6 comments
Labels
react react

Comments

@haizhilin2013
Copy link
Collaborator

[react] super()super(props)有什么区别?

@haizhilin2013 haizhilin2013 added the react react label Jul 16, 2019
@tiyunchen
Copy link

super() 可以让我们使用this来调用各种东西,
而super(props)可以让我们在this的基础上使用构造函数里面的东西, 或者从父元素那边传过来的一些属性

@mixj93
Copy link

mixj93 commented Sep 2, 2019

如果只调用了super(),那么this.propssuper()和构造函数结束之间仍是undefined

class Button extends React.Component {
  constructor(props) {
    super(); // 没有传 props
    console.log(props);      // {}
    console.log(this.props); // undefined 
  }
  // ...
}

@MagicalBridge
Copy link

react 中的class 是基于es6的规范实现的, 继承是使用extends关键字实现继承的,子类必须在constructor()中调用super() 方法否则新建实例
就会报错,报错的原因是 子类是没有自己的this对象的,它只能继承父类的this对象,然后对其进行加工,而super()就是将父类中的this对象继承给子类的,没有super() 子类就得不到this对象。

如果你使用了constructor就必须写super() 这个是用来初始化this的,可以绑定事件到this上
如果你想要在constructor中使用this.props,就必须给super添加参数 super(props)
注意,无论有没有 constructor,在render中的this.props都是可以使用的,这是react自动附带的
如果没有用到constructor 是可以不写的,react会默认添加一个空的constroctor.

@wjrhyw
Copy link

wjrhyw commented Apr 20, 2020

根据es6的规定,子类自己的构造函数中必须调用super,才能获得自己的this;所以只是super()的话,只能够让子类获取自己的this;但是props会是Undefined,如果传递了props给super,那么才会初始化子类自己的props

@shuch
Copy link

shuch commented May 4, 2020

@LiFeng007
Copy link

es6规定了子类中如果使用constructor构造函数,在super调用之前是没有自己的this,调用super用来初始化子类的this,至于在super中传props是为了可以通过this.props的形式访问父组件传过来的props

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
react react
Projects
None yet
Development

No branches or pull requests

7 participants