原博文地址: http://cheng.logdown.com/posts/2016/03/26/683329ide
当咱们像下面这样使用React
的ES6
class语法建立一个组件的时候:post
class MyClass extends React.component { constructor(){ super() } }
不由会提出两个问题:this
在constructor
里面调用super
是不是必要的?code
super
与super(props)
的区别?component
仅当存在constructor的时候必须调用super
,若是没有,则不用get
若是在你声明的组件中存在constructor
,则必需要加super
,举个栗子:it
class MyClass extends React.component { render(){ return <div>Hello { this.props.world }</div>; } }
这段代码完美无误,你不须要为之去调用super
,然而,若是在你的代码中存在consturctor
,那你必须调用:console
class MyClass extends React.component { constructor(){ console.log(this) //Error: 'this' is not allowed before super() } }
之因此会报错,是由于若不执行super
,则this
没法初始化。class
你也许会抱着侥幸心理猜想:那我直接写个空的constructor
就得了呗~,然而,在ES6
中的class
语法中,只要你的class
是子类,那必须得调用super
,换句话说,有constructor
就得有super
(固然,子类也能够没有constructor
)语法
仅当你想在constructor
内使用props才将props
传入super
。React
会自行props
设置在组件的其余地方(以供访问)。
将props
传入super
的做用是能够使你在constructor
内访问它:
class MyClass extends React.component{ constructor(props){ super(); console.log(this.props); // this.props is undefined } }
完善后:
class MyClass extends React.component{ constructor(props){ super(props); console.log(this.props); // prints out whatever is inside props } }
若是你只是想在别处访问它,是没必要传入props
的,由于React
会自动为你设置好:
class MyClass extends React.component{ render(){ // There is no need to call `super(props)` or even having a constructor // this.props is automatically set for you by React // not just in render but another where else other than the constructor console.log(this.props); // it works! } }