[译]React ES6 class constructor super()
原博文地址: http://cheng.logdown.com/posts/2016/03/26/683329 当我们像下面这样使用 class MyClass extends React.component { constructor(){ super() } } 不禁会提出两个问题:
解答一:仅当存在constructor的时候必须调用 如果在你声明的组件中存在 class MyClass extends React.component { render(){ return <div>Hello { this.props.world }</div>; } } 这段代码完美无误,你不需要为之去调用 class MyClass extends React.component { constructor(){ console.log(this) //Error: 'this' is not allowed before super() } } 之所以会报错,是因为若不执行 你也许会抱着侥幸心理猜测:那我直接写个空的 解答二仅当你想在 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 } } 如果你只是想在别处访问它,是不必传入 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! } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |