[译]React ES6 class constructor super()
当我们在写React时候 会用到ES6中的class语法,比较常见的情况如下: class MyClass extends React.Component{ constructor(){ super() } } 这里有两个问题:
解答 Q1:
只有当你有一个 class MyClass extends React.component{ render(){ return <div>Hello {this.props.world}</div> } } 上述代码完全符合规定所以你其实并没有必要去为你创建的每个React Component 调用 class MyClass extends React.component { constructor(){ console.log(this) //Error: 'this' is not allowed before super() } } 出现上述错误的原因是 class MyClass extends React.component { constructor(){} // Error: missing super() call in constructor } ES6的 解答Q 2:
假使你想获取到 看一下使用 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传递到constructor中 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! } } 我的理解是 总之 需要绑定 原文链接: React ES6 class constructor super() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |